Search Insert Position

LeetCode #35


Description:

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.

Example:

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

Idea:

重新实现lowerBound(), That's it.

Code:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return lowerBound(nums, target);
    }

    // 重新实现 lowerBound()
    int lowerBound(vector<int>& nums, int target){
        int begin=0;
        int end=nums.size();

        while(begin!=end){
            int mid = begin + (end-begin)/2;
            if(target>nums[mid]) begin = mid+1;
            else end = mid;
        }
        return begin;
    }
};

results matching ""

    No results matching ""