-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajorityElement.java
38 lines (30 loc) · 1014 Bytes
/
MajorityElement.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
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MajorityElement {
public static void main(String[] args) {
int[] arr = new int[]{1,1,1,1,1,13,4,4,5,9};
MajorityElement o1 = new MajorityElement();
System.out.print(o1.majority(arr));
}
public int majority(int[] arr) {
HashMap<Integer, Integer> mp = new HashMap<>();
int maxIndex = 0;
for (int j : arr) {
mp.put(j, mp.getOrDefault(j, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : mp.entrySet()){
int current = entry.getValue();
maxIndex = Math.max(current, maxIndex);
}
return getKeyByValue(mp, maxIndex);
}
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
}