首页 > 代码库 > [Leetcode] Search Insert Position

[Leetcode] 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

 

Tag:

Array; Binary Search

体会:

这道题,自己最开始的想法就是遍历,然后找到第一个 >= target 的位置,然后返回。代码写起来很简单,可是是O(N)的算法。然后看了别人的提示,才发现可以用binary search 降到O(lgN)。

关于跳出,循环到后面,low和high在同一个位置上,然后就是判断是在这个数的左边插入(>target)还是在当前位置插入(if < target)了。如果是要在左边插入,那就让high的位置从当前左移一位(i.e. high = mid - 1); 如果是在当前位置插入那就让low右移一位(low = mid + 1), 这样high和low就错开了,预示着我们找到位置了,然后然后low对应的位置就可以了。

class Solution {public:    int searchInsert(int A[], int n, int target) {       // iterative binary search        int low = 0;       int high = n - 1;       while (low <= high) {           int mid = low + (high - low) / 2;           if (A[mid] == target) {               return mid;           }           if (A[mid] > target) {               high = mid - 1;           } else {               low = mid + 1;           }       }       return low;    }};

 

[Leetcode] Search Insert Position