1. 1/2
public int majorityNumber(ArrayList<Integer> nums) {
if (nums == null || nums.isEmpty()) return -1;
// pair<key, count>
int key = -1, count = 0;
for (int num : nums) {
// re-initialize
if (count == 0) {
key = num;
count = 1;
continue;
}
// increment/decrement count
if (key == num) {
count++;
} else {
count--;
}
}
return key;
}2. 1/3
public int majorityNumber(ArrayList<Integer> nums) {
if (nums == null || nums.isEmpty()) return -1;
// pair
int key1 = -1, key2 = -1;
int count1 = 0, count2 = 0;
for (int num : nums) {
if (count1 == 0) {
key1 = num;
count1 = 1;
continue;
} else if (count2 == 0 && key1 != num) {
key2 = num;
count2 = 1;
continue;
}
if (key1 == num) {
count1++;
} else if (key2 == num) {
count2++;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int num : nums) {
if (key1 == num) {
count1++;
} else if (key2 == num) {
count2++;
}
}
return count1 > count2 ? key1 : key2;
}3. 1/K
public int majorityNumber(ArrayList<Integer> nums, int k) {
HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
if (nums == null || nums.isEmpty()) return -1;
// update HashMap
for (int num : nums) {
if (!hash.containsKey(num)) {
hash.put(num, 1);
if (hash.size() >= k) {
removeZeroCount(hash);
}
} else {
hash.put(num, hash.get(num) + 1);
}
} // reset
for (int key : hash.keySet()) {
hash.put(key, 0);
}
for (int key : nums) {
if (hash.containsKey(key)) {
hash.put(key, hash.get(key) + 1);
}
}
// find max
int maxKey = -1, maxCount = 0;
for (int key : hash.keySet()) {
if (hash.get(key) > maxCount) {
maxKey = key;
maxCount = hash.get(key);
}
}
return maxKey;
}
private void removeZeroCount(HashMap<Integer, Integer> hash) {
Set<Integer> keySet = hash.keySet();
for (int key : keySet) {
hash.put(key, hash.get(key) - 1);
}
/* solution 1 */
Iterator<Map.Entry<Integer, Integer>> it = hash.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> entry = it.next();
if(entry.getValue() == 0) {
it.remove();
}
}
}
寻找众数算法
本文介绍了三种不同的算法来解决寻找众数的问题。第一种算法适用于寻找出现次数超过一半的众数,第二种算法可以找出两个可能的候选众数,而第三种算法则能够找到出现频率最高的k个数中的一个。这些算法在遍历列表的过程中通过计数或投票的方式减少计算复杂度。
1万+

被折叠的 条评论
为什么被折叠?



