/* * 35. Search Insert Position * 2016-5-2 by Mingyang 这道题目偏简单 * 这只是常规的解法,后面我们来logn的解法 */ public int searchInsert(int[] nums, int target) { if (nums == null || nums.length == 0) return 0; if (target < nums[0]) return 0; for (int i = 0; i < nums.length; i++) { if (nums[i] >= target) return i; } return nums.length; } /* * 然后自己给出了一个Binary Search的解法, * 但是思路非常混乱 列下来以儆效尤 */ public int searchInsert1(int[] nums, int target) { int len = nums.length; if (nums == null || len == 0) return 0; if (target < nums[0]) return 0; if (target > nums[len - 1]) return len; int start = 0; int end = len - 1; while (start < end) { int mid = (start + end) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid; if (start + 1 == end) return end; } else { end = mid; } } return start; } // 史上最标准答案,最简洁的一种BS的方法,只需要了解为什么后面返回low就好了 public int searchInsert2(int[] nums, int target) { int low = 0, high = nums.length - 1; while (low <= high) { int mid = (low + high) / 2; if (nums[mid] == target) return mid; else if (nums[mid] > target) high = mid - 1; else low = mid + 1; } return low; }