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], 52

[1,3,5,6], 21

[1,3,5,6], 74

[1,3,5,6], 00

 

class Solution {

public:

    int searchInsert(int A[], int n, int target) {

        assert(A != NULL && n >= 0);

        int low = 0;

        int high = n - 1;

        while (low <= high) {

            int mid = low + (high - low)/2;

            if (target < A[mid]) {

                high = mid - 1;

            } else if (target > A[mid]) {

                low = mid + 1;

            } else {

                return mid;

            }

        }

        return low;

    }

};

当未找到目标元素时,low变量的就是该元素应该插入的位置,具体分析见我博文 二分查找的那些事儿 (第4题)

你可能感兴趣的:(LeetCode)