Labels

Wednesday, January 28, 2015

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

Naive Way: 一次遍历直到大于等于target。好傻的方法,我第一次就是这么写的。

    // O(n)
    public int searchInsert(int[] A, int target) {
        for(int i = 0;i < A.length;i++){
            if(A[i] == target){return i;}
            if(A[i] > target){return i;}
        }
        return A.length;
    }

Improved Way: 作为一个程序员看到这样的题没有想到binary search真是一件很忧伤的事情。第二次做法是改了一下binary search

// O(logn)
    public int searchInsert(int[] A, int target) {
        if(A.length==0){return 0;}
        int begin = 0, end = A.length-1;
        int middle = 0;
        if(target <= A[begin]){return 0;}
        if(target >= A[end]){return end+1;}
        while(begin < end){
            middle = (begin+end)/2;
            if(A[middle]==target)
                return middle;
            if(A[middle] < target && A[middle+1] >= target)
                return middle+1;
            if(A[middle] > target)
                end = middle;
            if(A[middle+1] < target)
                begin = middle+1;
        }
        return 0;
    }

类似要用binary search的思想的还有Remove-duplicates-from-sorted-array

 

No comments:

Post a Comment