码迷,mamicode.com
首页 > 其他好文 > 详细

Search Insert Position

时间:2014-12-03 23:06:05      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   os   sp   on   div   2014   

题目: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,有图为证

 

bubuko.com,布布扣

以下是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

标签:blog   http   io   ar   os   sp   on   div   2014   

原文地址:http://www.cnblogs.com/jarviswhj/p/4141328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!