-
Notifications
You must be signed in to change notification settings - Fork 130
/
Nby3_repeat_number.cpp
57 lines (53 loc) · 1.1 KB
/
Nby3_repeat_number.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
// Find out the number which has occurred more than N/3 times in an array where N is the array size.
int Solution::repeatedNumber(const vector<int> &A) {
int i = 0;
int first = INT_MAX, second = INT_MAX;
int count1 = 0, count2 = 0;
for(i = 0; i < A.size(); i++)
{
if(A[i] == first)
{
count1++;
}
else if(A[i] == second)
{
count2++;
}
else if(count1 == 0)
{
count1 = 1;
first = A[i];
}
else if(count2 == 0)
{
count2 = 1;
second = A[i];
}
else
{
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for(i = 0; i < A.size(); i++)
{
if(A[i] == first)
{
count1++;
}
if(A[i] == second)
{
count2++;
}
}
int n = A.size();
if(count1 > n/3)
{
return first;
}
else if(count2 > n/3)
return second;
return -1;
}