leetcode-search-for-a-range

题目大意

https://leetcode.com/problems/search-for-a-range/

一个排好序的数组中查找给定target元素的起始和结束位置

解题思路

二分查找。找>=target的元素的最小值和<=target元素的最大值

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
53
vector<int> searchRange(vector<int>& nums, int target) {
int r1, r2;
vector<int> ret;
int size = nums.size();
if(size == 0) {
ret.push_back(-1);
ret.push_back(-1);
return ret;
}
if(size == 1) {
if(nums[0] == target) {
ret.push_back(0);
ret.push_back(0);
} else {
ret.push_back(-1);
ret.push_back(-1);
}
return ret;
}
int L = 0;
int R = size;
int mid;
//find the minimum number of >= target
while(L + 1 < R) {
mid = (L + R - 1) / 2;
if(nums[mid] >= target) {
R = mid + 1;
} else {
L = mid + 1;
}
}
if(nums[L] != target) {
ret.push_back(-1);
ret.push_back(-1);
return ret;
}
r1 = L;
L = 0;
R = size;
while(L + 1 < R) {
mid = (L + R) / 2;
if(nums[mid] <= target) {
L = mid;
} else {
R = mid;
}
}
r2 = L;
ret.push_back(r1);
ret.push_back(r2);
return ret;
}

[L,R)是可能区间,每次循环以后更新L和R值仍保证此性质