-
Notifications
You must be signed in to change notification settings - Fork 0
/
数字在排序数组中出现的次数.txt
46 lines (41 loc) · 1.01 KB
/
数字在排序数组中出现的次数.txt
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
//统计一个数字在排序数组中出现的次数。
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int size = data.size();
if(size == 0)return 0;
int left = getleft(data,k);
int right = getright(data,k);
return right-left+1;
}
int getleft(vector<int>data,int k)
{
int start=0,end = data.size()-1;
int mid = start+(end-start)/2;
while(start<=end)
{
if(data[mid]<k)start=mid+1;
else
{
end = mid-1;
}
mid = start+(end-start)/2;
}
return start;
}
int getright(vector<int>data,int k)
{
int start=0,end = data.size()-1;
int mid = start+(end-start)/2;
while(start<=end)
{
if(data[mid]<=k)start=mid+1;
else
{
end = mid-1;
}
mid = start+(end-start)/2;
}
return end;
}
};