Search Insert Position

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 java


該題使用二分查找的策略進行實現。 spa

public class Solution {
    public int searchInsert(int[] A, int target) {
        int begin = 0;
        int end = A.length-1;
        while(begin <= end){
             int mid = (begin + end) / 2;
            if(A[mid] == target){
                return mid;
            }else if(A[mid] < target){
                begin = mid + 1;
            }else{
                end = mid - 1;
            }
        }
        //目標節點比mid位置的數據要小,根據二分查找應該將target的位置設置爲mid,故此返回end+1
         if(end < begin){
            return end + 1;
        }
       return begin + 1;
        
    }
}
相關文章
相關標籤/搜索