35. 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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

 
 
//binary search: Time: O(logn), Space: O(1)    
public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start <= end) {// <= 想清 [1,3] 2 和 [1,2] 3的情况
            int mid = start + (end - start) / 2;
            
            if (target > nums[mid]) {
                start = mid + 1;
            } else if (target < nums[mid]) {
                end = mid - 1;
            } else {
                return mid;
            }
        }
        
        return start;//最后end可能跑到start的前面 比如 [1,3] 2
    }

 

posted @ 2018-10-17 14:22  一丝清风一抹红尘  阅读(111)  评论(0编辑  收藏  举报