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<int>& 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<int>& 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 <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, 
                              const T& val, Compare comp);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 夜深人静寂寞时。你要不要来支烟。是不是还有点害怕。我想想。我忘了你不抽烟。那你更惨了。无事可做站在空荡荡的街道。还...
    arne阅读 390评论 0 1
  • 五月的灯火,闪亮夜空,悠悠淮河安静的躺在南阳大地上,已是深夜。一道人影若有若无,仿佛周身与夜色一体,数步...
    阿鱼的阿鱼阅读 107评论 0 0
  • 在我看来 梦想就像孩子吹出来的肥皂泡 它的存在就是为了让你我在闲来无事的时候戳着玩的 戳破了怎么办 不着急,很简单...
    2cb315bc1831阅读 139评论 0 0