- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathMajorityElement2.java
43 lines (41 loc) · 1.31 KB
/
MajorityElement2.java
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
packagemanas.pkg1.LeetCode;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.Arrays;
publicclassMajorityElem2 {
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
intn=Integer.parseInt(br.readLine());
int[] arr=newint[n];
inti;
for(i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
System.out.println(Arrays.toString(arr));
intele1=Integer.MIN_VALUE,ele2=Integer.MIN_VALUE,count1=0,count2=0;
for(i=0;i<n;i++) {
if (ele1 == arr[i]) count1++;
elseif (ele2 == arr[i]) count2++;
elseif (count1 == 0) {
ele1 = arr[i];
count1++;
}
elseif (count2 == 0) {
ele2 = arr[i];
count2++;
}
else {
count1--;
count2--;
}
}
count1=0;
count2=0;
for (i=0;i<n;i++){
if(arr[i]==ele1) count1++;
if(arr[i] == ele2) count2++;
}
if(count1 > n/3) System.out.println(ele1);
if(count2 > n/3) System.out.println(ele2);
}
}