package LeetCode;
import javafx.util.Pair;
import java.util.*;
public class LeetCode347 {
// 347. Top K Frequent Elements
// https://leetcode.com/problems/top-k-frequent-elements/description/
// æ¶é´å¤æåº¦: O(nlogk)
// 空é´å¤æåº¦: O(n + k)
private class PairComparator implements Comparator> {
@Override
public int compare(Pair p1, Pair p2){
if(p1.getKey() != p2.getKey())
return p1.getKey() - p2.getKey();
return p1.getValue() - p2.getValue();
}
}
// nums = [1,1,1,2,2,3], k = 2
public List topKFrequent(int[] nums, int k) {
if(k <= 0)
throw new IllegalArgumentException("k should be greater than 0");
// ç»è®¡æ¯ä¸ªå
ç´ åºç°çé¢ç
HashMap freq = new HashMap<>();
for(int i = 0 ; i < nums.length ; i ++)
if(freq.containsKey(nums[i]))
freq.put(nums[i], freq.get(nums[i]) + 1);
else
freq.put(nums[i], 1);
if(k > freq.size())
throw new IllegalArgumentException("k should be less than the number of unique numbers in nums");
// æ«æfreq,ç»´æ¤å½ååºç°é¢çæé«çk个å
ç´
// å¨ä¼å
éåä¸,æç
§é¢çæåº,æä»¥æ°æ®å¯¹æ¯ (é¢ç,å
ç´ ) çå½¢å¼
// è¿éçæ¯æå°éå
PriorityQueue> pq = new PriorityQueue<>(new PairComparator());
for(Integer num: freq.keySet()){
int numFreq = freq.get(num);
// ç»´æ¤k个å¼ï¼å½åå
ç´ æ¯ä¼å
éååºç°çé¢çè¦é«ï¼é£å°±åºéï¼
if(pq.size() == k){
if(numFreq > pq.peek().getKey()){
pq.poll();
pq.add(new Pair(numFreq, num));
}
} else
pq.add(new Pair(numFreq, num));
}
ArrayList res = new ArrayList<>();
while(!pq.isEmpty())
res.add(pq.poll().getValue());
return res;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
new LeetCode347().topKFrequent(nums, 2);
}
}