http://www.lintcode.com/en/problem/majority-number-iii/#
数组中有且仅有一个出现次数大于 1/k,找出来
遇到k个就抵消一个
public class Solution {
public int majorityNumber(ArrayList<Integer> nums, int k) {
// write your code
HashMap<Integer, Integer> map = new HashMap();
for (int n : nums) {
if (map.containsKey(n)) {
map.put(n, map.get(n) + 1);
} else if (map.size() < k) {
map.put(n, 1);
} else {
remove(map);
}
}
if (map.size() == 0) {
return Integer.MIN_VALUE;
}
for (int key : map.keySet()) {
map.put(key, 0);
}
int max = 0;
int cnt = 0;
for (int i = 0; i < nums.size(); i++) {
if (map.containsKey(nums.get(i))) {
map.put(nums.get(i), map.get(nums.get(i)) + 1);
}
}
for (int key : map.keySet()) {
if (map.get(key) > cnt) {
cnt = map.get(key);
max = key;
}
}
return max;
}
private void remove(HashMap<Integer, Integer> map) {
ArrayList<Integer> list = new ArrayList();
for (int key : map.keySet()) {
list.add(key);
}
for (int key : list) {
map.put(key, map.get(key) - 1);
if (map.get(key) == 0) {
map.remove(key);
}
}
}
}