2016年7月1日星期五

[LintCode] #60 Search Insert Position

attention: if target > all elements in A T_T

public class Solution {
    /** 
     * param A : an integer sorted array
     * param target :  an integer to be inserted
     * return : an integer
     */
    public int searchInsert(int[] A, int target) {
        // write your code here
        if (A == null || A.length == 0) {
            return 0;
        }
        
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] >= target) {
                end = mid;
            } else {
                start = mid;
            }
        }
        
        if (A[start] >= target) {
            return start;
        } else if (A[end] >= target){
            return end;
        } else {
            return end + 1; // 1st attempt failed: target > all elements in A
        }
    }
}


没有评论:

发表评论