-
Notifications
You must be signed in to change notification settings - Fork 0
/
20180201getnumberofk
46 lines (46 loc) · 1.09 KB
/
20180201getnumberofk
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 count=0;
if(data.size()>0){
int s=0,e=data.size()-1;
int first=firstk(data,k,s,e);
int last=lastk(data,k,s,e);
if(first>-1&&last>-1)
count=last-first+1;
}
return count;
}
int firstk(vector<int> data,int k,int s,int e){
if(s>e)
return -1;
int m=(s+e)/2;
if(data[m]==k){
if(m>0&&data[m-1]!=k||m==0)
return m;
else
e=m-1;
}
else if(data[m]>k)
e=m-1;
else
s=m+1;
return firstk(data,k,s,e);
}
int lastk(vector<int> data,int k,int s,int e){
if(s>e)
return -1;
int m=(s+e)/2;
if(data[m]==k){
if(m<data.size()-1&&data[m+1]!=k||m==data.size()-1)
return m;
else
s=m+1;
}
else if(data[m]<k)
s=m+1;
else
e=m-1;
return lastk(data,k,s,e);
}
};