-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMostFrequent.java
45 lines (34 loc) · 1.12 KB
/
MostFrequent.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
44
45
/* Find the most frequent integer in an array */
import java.util.*;
import java.lang.*;
public class MostFrequent {
private Map<Integer, Integer> itemCount;
public int findMostFrequent(Integer[] arr) {
itemCount = new HashMap<Integer, Integer>();
countElement(arr);
Integer max = itemCount.get(arr[0]);
Integer maxKey = arr[0];
for (Integer key : itemCount.keySet()) {
if (itemCount.get(key) > max) {
max = itemCount.get(key);
maxKey = key;
}
}
return maxKey;
}
public void countElement(Integer[] arr) {
for (Integer element : arr) {
Integer count = itemCount.get(element);
if (count == null) {
itemCount.put(element, 0);
} else {
itemCount.put(element, count + 1);
}
}
}
public static void main(String args[]) {
Integer[] array = {1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5};
MostFrequent mostFrequent = new MostFrequent();
System.out.println(mostFrequent.findMostFrequent(array));
}
}