35. Search Insert Position

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; // [left, right]
while (left <= right) {
int mid = (left + right) >>> 1;
if (target > nums[mid]) {
left = mid + 1; // 此处不断推进 left 索引能保证最后 left 停留的位置能够合法放置 target
} else if (target < nums[mid]) {
right = mid - 1; // 此处不用 mid 是防止死循环,虽然 right 把正确的值排除了,但是最后返回的 left
} else {
return mid;
}
}

// now: right, left
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; // [left, right)
while (left < right) {
int mid = (left + right) >>> 1;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}

// now: left equals to right
return left;
}
}

References

35. Search Insert Position
剑指 Offer II 068. 查找插入位置