35. Search Insert Position
class Solution { public int searchInsert(int[] nums, int target) { int low = 0; int high = nums.length - 1; while( low <= high){ int mid = low + (high - low) / 2; if(nums[mid] == target){ return mid; }else{ if(nums[mid] < target){ low = mid + 1; }else{ high = mid - 1; } } } return low; } }
Index of the target or
index of Smallest larger than the target
class Solution { public int searchInsert(int[] nums, int target) { // sanity check if(nums == null || nums.length == 0) return 0; if(target < nums[0]) return 0; if(target > nums[nums.length - 1]) return nums.length; int left = 0; int right = nums.length - 1; while(left < right){ int mid = left + (right - left) / 2; if(nums[mid] == target){ return mid; }else if(nums[mid] < target){ left = mid + 1; }else{ right = mid; } } return left; } }
下面这几个例子都要考虑到才行, 面试的时候也是一样, 自己把这些情况都要考虑到, 面试的时候很可能不给你这么多的例子,
面试官可能指望你自己考虑周全, 把所有或者大部分的corner case , edge case 都想到
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
posted on 2018-07-18 08:15 猪猪🐷 阅读(96) 评论(0) 收藏 举报
浙公网安备 33010602011771号