34. Find First and Last Position of Element in Sorted Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public int[] searchRange(int[] nums, int target) {
int startIndex = findStartIndex(nums, target);
if (startIndex == -1) {
return new int[]{-1, -1};
} else {
return new int[]{startIndex, findEndIndex(nums, target)};
}
}

private int findEndIndex(int[] nums, int target) {
int left = 0, right = nums.length - 1; // [left, right]
while (left <= right) {
int mid = (left + right) >>> 1;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}

// now: right, left
if (right == -1 || nums[right] != target) {
return -1;
}

return right;
}

private int findStartIndex(int[] nums, int target) {
int left = 0, right = nums.length - 1; // [left, right]
while (left <= right) {
int mid = (left + right) >>> 1;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
right = mid - 1;
}
}

// now: right, left
if (left == nums.length || nums[left] != target) {
return -1;
}

return left;
}
}

Binary Search

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int[] searchRange(int[] nums, int target) {
int firstIndex = findFirstIndex(nums, target);
if (firstIndex >= nums.length || nums[firstIndex] != target) {
return new int[]{-1, -1};
}

int nextValueIndex = findFirstIndex(nums, target + 1);
return new int[]{firstIndex, nextValueIndex - 1};
}

private int findFirstIndex(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) { // 注意此处需要使用小于等于,保证数组中所有元素参与比较,否则 [1] 这样的数组无法进入循环,[2, 2] 这样的数组在搜索 3 时 left 会停留在最后一个索引上,导致结果错误
int mid = (left + right) >>> 1;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
right = mid - 1; // 注意此处即使搜索到了目标值也要继续搜索,因为我们的搜索目标是第一个位置,而不是搜索到任意一个就返回
}
}

// now: right, left
return left;
}
}

注意此题是搜索第一个和最后一个位置而不是搜索插入位置,所以需要比较最后停留的位置的值是否为目标值。

References

34. Find First and Last Position of Element in Sorted Array