-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathMajorityElement.java
More file actions
39 lines (31 loc) · 1.09 KB
/
MajorityElement.java
File metadata and controls
39 lines (31 loc) · 1.09 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
package Programs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MajorityElement {
private static List<Integer> majorityElement(int[] v){
int n = v.length;
List<Integer> ans = new ArrayList<>();
int min = n/3 +1;
HashMap<Integer,Integer> mpp = new HashMap<>();
for (int j : v) {
int val = mpp.getOrDefault(j, 0);
mpp.put(j, val + 1);
if (mpp.get(j) == min) {
ans.add(j);
}
if(ans.size() == 2)
break;
}
return ans;
}
public static void main(String[] args) {
int[] arr = {1,2,2,2,1,1};
List<Integer> ans = majorityElement(arr);
System.out.print("The majority elements are: ");
for (Integer an : ans) {
System.out.print(an + " ");
}
System.out.println();
}
}