[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], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

思路:很明显这里看见sorted array第一反应就是二分查找,这里有两个小问题要注意下:

1.边界问题,因为这里要求如果没找到也是要返回一个应有的下标。

2.很多人喜欢用mid=(start+end)/2,但这样有可能会造成和的溢出,所以这里用了start+(end-start)>>1,移位也更高效。

完成时长:20分钟。

一次AC,有图为证

 

以下是AC代码:

class Solution {
public:
    int searchInsert(int A[], int n, int target) {
        if(A == NULL || n<1)   return 0;
        
        int start=0;
        int end=n-1;
        int mid=start+((end-start)>>1);
        
        while(start <= end)
        {
            mid=start+((end-start)>>1);
            
            if(A[mid]>target)
            {
                end=mid-1;
            }
            else if(A[mid]<target)
            {
                start=mid+1;
            }
            else
            {
                return mid;
            }
        }
        
        if(A[mid]>target)   return mid;
        if(A[mid]<target)   return mid+1;
    }
};

  

  本博客内容与代码均为作者Jarvis原创,如若转载请注明。

posted @ 2014-12-03 21:21  Jarvis_Wu  阅读(163)  评论(0编辑  收藏  举报