首页 > 代码库 > Search Insert Position

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,但这样有可能会造成mid访问溢出,所以这里用了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)>>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;    }};

  

Search Insert Position