Sunday, July 19, 2015

035 - Search Insert Position

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

Hide Tags

Array Binary Search

Hide Similar Problems

(M) Search for a Range

 

二分查找,稍微特殊一点的地方就是要判断mid与mid+1之间的区间。

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int sz=nums.size();
        if(sz)
        {
            if(target<nums[0])
                return 0;
            else if(target>nums[sz-1])
                return sz;

            else
                return search(nums, target, 0, sz-1);
        }
    }
private:
    int search(vector<int>& nums, int target, int start, int end)
    {
        if(target == nums[start])
            return start;
        if(target == nums[end])
            return end;

        int mid = (start+end)/2;
        if((target > nums[mid])&&(target < nums[mid+1]))
            return mid+1;

        if(target <= nums[mid])
            return search(nums, target, start, mid);
        if(target >= nums[mid+1])
            return search(nums, target, mid+1, end);
    }
};

No comments:

Post a Comment