左神算法 在数组中找到出现次数大于N/K的数
程序员文章站
2022-03-13 12:32:35
...
左神的代码写的很好,时间复杂度是O(N*K),额外空间复杂度O(K),用map集合保存K个不同的值。一、如果map的大小不超过K,遍历到相同的,value加1,不同的,添加进去。用map.containskey判断是否在容器中,比用数组方便。
二、如果map大小达到K,遍历到相同的,所有键的值减1,如果值变成0,要删除。这时候引出一全体键值都减1的函数,左神用了遍历map,如果要删除的键放进一个链表里。
三、判断map中剩下的值出现次数是否大于N/K
感谢左神,代码写的太漂亮了,好好学习!!!
public class FindKMajority {
public static void printKMajor(int[] arr, int K) {
if (K < 2) {
System.out.println("the value of K is invalid.");
return;
}
HashMap<Integer, Integer> cands = new HashMap<Integer, Integer>();
for (int i = 0; i != arr.length; i++) {
if (cands.containsKey(arr[i])) {
cands.put(arr[i], cands.get(arr[i]) + 1);
} else {
if (cands.size() == K - 1) {
allCandsMinusOne(cands);
} else {
cands.put(arr[i], 1);
}
}
}
HashMap<Integer, Integer> reals = getReals(arr, cands);
boolean hasPrint = false;
for (Entry<Integer, Integer> set : cands.entrySet()) {
Integer key = set.getKey();
if (reals.get(key) > arr.length / K) {
hasPrint = true;
System.out.print(key + " ");
}
}
System.out.println(hasPrint ? "" : "no such number.");
}
public static void allCandsMinusOne(HashMap<Integer, Integer> map) {
List<Integer> removeList = new LinkedList<Integer>();
for (Entry<Integer, Integer> set : map.entrySet()) {
Integer key = set.getKey();
Integer value = set.getValue();
if (value == 1) {
removeList.add(key);
}
map.put(key, value - 1);
}
for (Integer removeKey : removeList) {
map.remove(removeKey);
}
}
public static HashMap<Integer, Integer> getReals(int[] arr,
HashMap<Integer, Integer> cands) {
HashMap<Integer, Integer> reals = new HashMap<Integer, Integer>();
for (int i = 0; i != arr.length; i++) {
int curNum = arr[i];
if (cands.containsKey(curNum)) {
if (reals.containsKey(curNum)) {
reals.put(curNum, reals.get(curNum) + 1);
} else {
reals.put(curNum, 1);
}
}
}
return reals;
}
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 1, 1, 2, 1 };
printHalfMajor(arr);
int K = 4;
printKMajor(arr, K);
}
}