LeetCode: 35. Search for insertion position
Simple dichotomy
Continuously use dichotomy to find the first subscript greater than or equal to target
AC Code
Because it is possible that the position of the last element of the array is next to what we are looking for, the right boundary is len
class Solution {
public int searchInsert(int[] nums, int target) {
int len = nums.length;
// 可能插入末尾 >> 末尾即 len
// 因为有可能数组的最后一个元素的位置的下一个是我们要找的,故右边界是 len
int left = 0, right = len;
while(left < right) {
int mid = left + (right - left) / 2;
if(nums[mid] > target) {
right = mid;
} else if(nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
}
return left;
}
}