友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
Example 1:
Input: nums = [5,7,7,8,8,10]
, target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10]
, target = 6
Output: [-1,-1]
思路分析
可以直接使用二分查找,搜索两次。
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
public static int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[]{-1, -1};
}
// 搜索左边界
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (target < nums[mid]) {
right = mid - 1;
} else if (nums[mid] == target) {
right = mid - 1; // 注意这里的处理
}
}
if (left == nums.length) {
return new int[]{-1, -1};
}
int i1 = -1;
if (nums[left] == target) {
i1 = left;
} else {
return new int[]{-1, -1};
}
// 搜索右边界
left = 0;
right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (target < nums[mid]) {
right = mid - 1;
} else if (nums[mid] == target) {
left = mid + 1; // 注意这里的处理
}
}
if (left - 1 < 0) {
return new int[]{-1, -1};
}
int i2 = -1;
if (nums[left - 1] == target) {
i2 = left - 1;
} else {
return new int[]{-1, -1};
}
return new int[]{i1, i2};
}