35. Search Insert Position #Array (Medium)

Problem:

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

Solution:

Actually, we are going to find the lower bound in the array.
Based on binary search, but have some differences.

class Solution {
public:
    int searchInsert(vector& nums, int target) {
        int start = 0;
        int end = nums.size(); //not num.size() - 1, think why
        int index ;
        while (start < end)
        {
            index = (start + end) / 2;
            if (nums[index] == target) return index;
            else if (nums[index] > target) end = index; //not index + 1
            else start = index + 1;
        }
        return start;
    }
};

LeetCode Discussion

Neater solution:

Actually, what we need here is std::lower_bound in C++ STL, which returns an iterator pointing to the first element that does not less than target. And then, things are quite simple:

class Solution {
public:
    int searchInsert(vector& nums, int target) {
        return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    }
};

LeetCode Discussion

Memo:

lower_bound Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

template 
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, 
                              const T& val, Compare comp);

你可能感兴趣的:(35. Search Insert Position #Array (Medium))