首页 > 其他 > 详细

leetcode 题解 || Search Insert Position 问题

时间:2015-03-25 12:16:08      阅读:195      评论:0      收藏:0      [点我收藏+]

problem:

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

Hide Tags
 Array Binary Search
在已序数组中找到一个数的下标,如果该数不在数组中,找出其应该插入的位置

thinking:

(1)又是对二分搜索的变形,策略很简单,不光要判断 A[mid]  是否等于arget,还要判断target是否落在区间(mid-1,mid+1)内,即:

 if(A[mid]==target || (A[mid-1]<target&&target<A[mid+1]) )
        {
            if(A[mid]==target || target<A[mid])
                return mid;
            else
                return mid+1;
        }
(2)注意边界条件比较多
code:

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
       
        if(n==0)//空数组
            return 0;
        if(n==1)//一个元素
        {
            if(A[0]>=target)
                return 0;
            else 
                return 1;
        }//if
        if(A[0]>=target)//target落在数组最前方
            return 0;
        if(A[n-1]<target)//target落在最后面
            return n;
        int res=binary_search(A,0,n-1,target);
        return res;
    }
protected:
    int binary_search(int A[], int left, int right, int target)
    {
        if(left>right)            
            return -1;
        int mid = (left+right)/2;
        if(A[mid]==target || (A[mid-1]<target&&target<A[mid+1]) )
        {
            if(A[mid]==target || target<A[mid])
                return mid;
            else
                return mid+1;
        }
        else if(A[mid]>target)
           return binary_search(A,left,mid-1,target);
        else
           return binary_search(A,mid+1,right,target);
    }

           
};





leetcode 题解 || Search Insert Position 问题

原文:http://blog.csdn.net/hustyangju/article/details/44618471

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!