-
Notifications
You must be signed in to change notification settings - Fork 22
/
FindMaxOccurence of a number in a given Array
54 lines (46 loc) · 2.2 KB
/
FindMaxOccurence of a number in a given Array
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
package Amazon;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class FindMaxOccurenceNumber {
public static void main(String[] args)
{
int[] arr = { 1, 2, 2, 3, 3, 2, 5, 0, 1, 5, 2, 3, 3, 5, 5, 3};
// There can be more than on most frequent number. What should we do ?
// Assuming we need to print all of them.
// The key of the map is the element and the value of the map is the count of that
// element in the MAP
// That is Map<element, its count>
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < arr.length; i++ )
{
if (countMap.containsKey(arr[i]))
{
int c = countMap.get(arr[i]);
c++;
countMap.put(arr[i], c);
} else {
countMap.put(arr[i], 1);
}
}
Iterator<Entry<Integer,Integer>> itr = countMap.entrySet().iterator();
List<Integer> currMaxKeys = new ArrayList<Integer>();
int currMax = Integer.MIN_VALUE;
while ( itr.hasNext() )
{
Entry<Integer,Integer> pair = itr.next();
if ( pair.getValue() > currMax)
{
currMaxKeys.clear();
currMaxKeys.add(pair.getKey()); // Store the key
currMax = pair.getValue();
} else if ( pair.getValue() == currMax) {
currMaxKeys.add(pair.getKey()); // If there is a tie, then add the second as well
}
}
System.out.println("Result is : " + currMaxKeys + " with occurence : " + currMax);
}
}