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.
Note
There is only one majority number in the array.
Example
For [3,1,2,3,2,3,3,4,4,4] and k = 3, return 3
Challenge
思路和Majority NumberII 一样,维护k-1个candidate 在map里面,key为数字值,value为出现次数。先找到这k-1个candidate后,扫描所有元素,如果该元素存在在map里面,update map;如果不存在,1: 如果map里面有值为count= 0,那么删除掉这个元素,加入新元素;2:map里面没有0出现,那么就每个元素的count--
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;
}