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 n = nums.length;
int left = 0;
int right = n - 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 - 1;
}
}
return left;
}
}

Remarks:

  1. TC: $O(\log n)$
  2. In a standard binary search senario, left is always the first index that is >=target; right is at the last index that is <target. Why? because the while condition is left <= right, and the loop ends when left > right.