您的位置:首页 > 其它

leetcode-35 Search Insert Position

2015-03-31 10:16 411 查看
简单的二分查找,注意找不到的情况下,target应该插入的位置

迭代的解法:

<span style="font-family:Microsoft YaHei;font-size:14px;">int searchInsert(int A[], int n, int target) {
    int low = 0,high = n-1;
    while(low <= high){
        int mid = (low + high)/2;
        if(A[mid] == target) return mid;
        else if(A[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    if(low > high)
        return high + 1;//或者return low,这个判断需要有
}</span>


也可以递归:

<span style="font-family:Microsoft YaHei;font-size:14px;">int helper(int A[],int start,int end,int target){
    if(start > end) return start;
    int mid = (start + end) / 2;
    if(A[mid] == target) return mid;
    else if(A[mid] > target) return helper(A,start,mid - 1,target);
    else return helper(A,mid+1,end,target);
}
int searchInsert(int A[], int n, int target) {
    return helper(A,0,n-1,target);
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: