-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path38数字在排序数组中出现的次数.cpp
57 lines (53 loc) · 1.28 KB
/
38数字在排序数组中出现的次数.cpp
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
54
55
56
57
//38
// 统计一个数字在排序数组中出现的次数。
//思路:已排序 ---> 二分查找
// 两次二分查找
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k)
{
if (data.empty())
return 0;
int first = GetNumberOfKFirst(data, k);
int last = GetNumberOfKLast(data, k);
if (first == -1 || last == -1)
return 0;
return last - first + 1;
}
int GetNumberOfKFirst(vector<int> data, int k)
{
int left = 0, right = data.size() - 1;
int mid;
while(left <= right)
{
mid = (left + right) >> 1;
if (data[mid] < k)
left = mid + 1;
else if (data[mid] > k)
right = mid - 1;
else if (mid == 0 || data[mid-1] != k)
return mid;
else
right = mid - 1;
}
return -1;//没找着first
}
int GetNumberOfKLast(vector<int> data, int k)
{
int left = 0, right = data.size() - 1;
int mid;
while(left <= right)
{
mid = (left + right) >> 1;
if (data[mid] < k)
left = mid + 1;
else if (data[mid] > k)
right = mid - 1;
else if (mid == data.size() - 1 || data[mid+1] != k)
return mid;
else
left = mid + 1;
}
return -1;//没找着last
}
};