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. Find it.
There is only one majority number in the array.
For [3,1,2,3,2,3,3,4,4,4] and k = 3, return 3
O(n) time and O(k) extra space
剩下的map裏面的值都有可能是majority,所以重新掃描數組,記錄下每一個元素出現次數,次數最大的就是majority
public int majorityNumber(ArrayList<Integer> nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int totalCan = 0;
int i = 0;
while (totalCan < k && i < nums.size()) {
int cur = nums.get(i);
if (map.containsKey(cur)) {
map.put(cur, map.get(cur) + 1);
} else {
map.put(cur, 1);
totalCan++;
}
i++;
}
while (i < nums.size()) {
int cur = nums.get(i);
if (map.containsKey(cur)) {
map.put(cur, map.get(cur) + 1);
} else { // not match any candidate
if (map.values().contains(0)) {
map.put(cur, 1);
Integer zeroKey = null;
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue().equals(0)) {
zeroKey = (Integer) entry.getKey();
break;
}
}
map.remove(zeroKey);
} else {
for (Map.Entry entry : map.entrySet()) {
map.put((Integer) entry.getKey(), (Integer) entry.getValue() - 1);
}
}
}
i++;
}
Map<Integer, Integer> newMap = new HashMap<Integer, Integer>();
int maxCount = 0;
int maxNum = 0;
for (int j = 0; j < nums.size(); j++) {
int cur = nums.get(j);
if (map.containsKey(cur)) {
newMap.put(cur, newMap.get(cur) == null ? 1 : newMap.get(cur) + 1);
if (newMap.get(cur) > maxCount) {
maxCount = newMap.get(cur);
maxNum = cur;
}
}
}
return maxNum;
}