Binary Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int searchInsert(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = (left + right) >>> 1; if (target > nums[mid]) { left = mid + 1; } else if (target < nums[mid]) { right = mid - 1; } else { return mid; } }
return left; } }
|
Binary Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int searchInsert(int[] nums, int target) { int left = 0, right = nums.length; while (left < right) { int mid = (left + right) >>> 1; if (nums[mid] < target) { left = mid + 1; } else { right = mid; } }
return left; } }
|
References
35. Search Insert Position
剑指 Offer II 068. 查找插入位置