LintCode : 搜索插入位置

LintCode : 搜索插入位置

给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。

你可以假设在数组中无重复元素。

二分法。


class Solution {
    /** * param A : an integer sorted array * param target : an integer to be inserted * return : an integer */
public:
    int searchInsert(vector<int> &A, int target) {
        // write your code here
        int low = 0;
        int high = A.size() - 1;
        int mid;
        while(low <= high){
            mid = (low + high) / 2;

            if (A[mid] > target) high = mid - 1;
            else if (A[mid] < target) low = mid + 1;
            else return mid;
        }
        return low;
    }
};


你可能感兴趣的:(lintcode)