35. Search Insert Position

https://leetcode.com/problems/search-insert-position/description/

总结好 Binary Search 通用写法后,这道题目非常容易。Summary 里的 Binary Search 实现方式可以保证循环结束时,

  • start == end + 1
  • 如果 target 在 array 范围内,nums[start] > target && nums[end] < target
  • 如果 target 大于 array 中所有值,start == nums.length && end = nums.length - 1
  • 如果 target 小于 array 中所有值,start == 0 && end == -1

代码:

public int searchInsert(int[] nums, int target) {
    if (nums == null || nums.length == 0) {
        return -1;
    }

    int left = 0;
    int right = nums.length - 1;
    int mid;

    while (left <= right) {
        mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return left;
}

你可能感兴趣的:(35. Search Insert Position)