-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajority Element II.java
More file actions
54 lines (52 loc) · 1.2 KB
/
Copy pathMajority Element II.java
File metadata and controls
54 lines (52 loc) · 1.2 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
import java.util.* ;
import java.io.*;
import java.util.ArrayList;
public class Solution
{
public static ArrayList<Integer> majorityElementII(ArrayList<Integer> arr)
{
// Write your code here.
int count1=0;
int count2=0;
int ele1=0;
int ele2=0;
for(Integer i : arr){
if(ele1==i){
count1++;
}
else if(ele2==i){
count2++;
}
else if(count1==0){
ele1=i;
count1++;
}
else if(count2==0){
ele2=i;
count2++;
}
else{
count1--;
count2--;
}
}
count1=0;
count2=0;
for(Integer i : arr){
if(ele1==i){
count1++;
}
if(ele2==i){
count2++;
}
}
ArrayList<Integer> ans = new ArrayList<>();
if(count1>Math.floor(arr.size()/3)){
ans.add(ele1);
}
if(!ans.contains(ele2) && count2>Math.floor(arr.size()/3)){
ans.add(ele2);
}
return ans;
}
}