forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNby3Repeat.java
More file actions
70 lines (55 loc) · 1.23 KB
/
Nby3Repeat.java
File metadata and controls
70 lines (55 loc) · 1.23 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
package Array;
import java.util.List;
/**
* Author - archit.s
* Date - 06/09/18
* Time - 12:45 PM
*/
public class Nby3Repeat {
public int repeatedNumber(final List<Integer> a) {
if(a.size()<3){
return a.get(0);
}
int v1 = Integer.MAX_VALUE;
int v2 = Integer.MAX_VALUE;
int count1 = 0;
int count2 = 0;
int N = a.size();
for(int i=0;i<N;i++){
if(v1 == a.get(i)){
count1++;
}
else if( v2 == a.get(i)){
count2++;
}
else if(count1 == 0){
v1 = a.get(i);
count1=1;
}
else if(count2 == 0){
v2 = a.get(i);
count2 =1;
}
else {
count1-=1;
count2-=1;
}
}
count1 = 0;
count2 = 0;
for (Integer anA : a) {
if (anA == v1) {
count1++;
} else if (v2 == anA) {
count2++;
}
}
if(count1 > N/3){
return v1;
}
if(count2 > N/3){
return v2;
}
return -1;
}
}