【ATT】Search Insert Position

Q: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

A: 在有序数组中找到等于target数或者最小的大于target的数的位置。

二分。

        if(target>A[n-1])
            return n;     这个判断是必不可少的。
否则此时返回的的是n-1.

//注意:+优先级大于>>.

int mid = begin+(end-begin)>>1; 是错误的。!!  
    int searchInsert(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case
        //find the pos of first one in array which larger than target or equal to target
        if(target>A[n-1])
            return n;
        int begin = 0, end = n-1;
        while(begin<end)
        {
            int mid = begin+(end-begin)/2;  
            if(A[mid]<target)
                begin = mid+1;
            else
                end = mid;
                
        }
        
        return begin;
        
    }

  

posted @ 2013-10-06 22:26  summer_zhou  阅读(162)  评论(0编辑  收藏  举报