Leetcode(35) 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


代码如下

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        int i = 0;
        int j = n - 1;
        int mid = 0;
        while (i <= j) {
            mid = i + ((j - i) >> 1); //1如果不确定运算符优先级可以加括号,2除法可以用右移。
            if (A[mid] < target)
                i = mid + 1;
            else if (A[mid] > target)
                j = mid -1;
            else 
                return mid;
        }
        
        return i; //简化了之前的写法:if (target>A[mid]) return mid + 1; else return mid;
        //因为如果找不到mid的话,i和j将出现交叉,i是刚好比target大的数,j是刚好比target小的数。所以return i或者return j+1都对。
    }
};


你可能感兴趣的:(LeetCode)