-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathN\3 Repeat Number
46 lines (40 loc) · 1.19 KB
/
N\3 Repeat Number
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
You’re given a read only array of n integers. Find out if any integer occurs more than n/3 times in the array in linear time and constant additional space.
If so, return the integer. If not, return -1.
If there are multiple solutions, return any one.
Example :
Input : [1 2 3 1 1]
Output : 1
1 occurs 3 times which is more than 5/3 times.
**************************************************************************************************************
int Solution::repeatedNumber(const vector<int> &A) {
int n=A.size();
int element1=INT_MAX,element2=INT_MAX;
int count1=0,count2=0,i;
for(i=0;i<n;i++){
if(count1>0 && A[i]==element1){
count1+=1;
}else if(count2>0 && A[i]==element2){
count2+=1;
}else if(count1==0){
element1=A[i];
count1=1;
}else if(count2==0){
element2=A[i];
count2=1;
}else{
count1--;
count2--;
}
}
if(count1==0 && count2==0)
return -1;
count1 = 0;
count2= 0;
for(int i=0 ; i<n ; i++){
if(A[i] == element1) count1++;
else if(A[i] == element2) count2++;
}
if(count1 > n/3) return element1;
else if (count2 > n/3) return element2;
else return -1;
}