LeetCode: Search Insert Position

思路:二分搜索,对于当前元素A[mid],如果A[mid] > target,则应该从left 到 mid-1进行搜索,但是如果A[mid-1] < target 则插入位置就是mid这里,返回mid值,注意向左搜到mid==0时,还没有确定好位置,就应该返回0,并入到一起就是return mid,右边情况的分析类似。

code:

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int left = 0, right = n-1;
        while(left <= right){
            int mid = (left + right)>>1;
            if(A[mid] == target)return mid;
            else if(A[mid] > target){
                if(mid == 0 || A[mid-1] < target)return mid;
                right = mid - 1;
            }
            else{
                if(mid == n-1 || A[mid+1] > target)return mid+1;
                left = mid + 1;
            }
        }
    }
};


你可能感兴趣的:(LeetCode: Search Insert Position)