Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array.
Example
Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.
public class Solution {
/**
* @param nums: A list of integers
* @param k: As described
* @return: The majority number
*/
public int majorityNumber(ArrayList<Integer> nums, int k) {
HashMap<Integer, Integer> counters = new HashMap<Integer, Integer>();
for (Integer num : nums) {
if (!counters.containsKey(num)) {
counters.put(num, 1);
} else {
counters.put(num, counters.get(num) + 1);
}
if (counters.size() >= k) {
removeKey(counters);
}
}
// corner case
if (counters.size() == 0) {
return Integer.MIN_VALUE;
}
// re-count the numbers
for (Integer num : counters.keySet()) {
counters.put(num, 0);
}
for (Integer num : nums) {
if (counters.containsKey(num)) {
counters.put(num, counters.get(num) + 1);
}
}
// find majority
int maxCounter = 0, maxKey = 0;
for (Integer num : counters.keySet()) {
if (counters.get(num) > maxCounter) {
maxCounter = counters.get(num);
maxKey = num;
}
}
return maxKey;
}
private void removeKey(HashMap<Integer, Integer> counters) {
Set<Integer> keySet = counters.keySet();
List<Integer> removeList = new ArrayList<>();
for (Integer key : keySet) {
counters.put(key, counters.get(key) - 1);
if (counters.get(key) == 0) {
removeList.add(key);
}
}
for (Integer key : removeList) {
counters.remove(key);
}
}
}