小根堆

  • map统计词频
  • 小根堆用出现的次数排序

image.png
image.png

小根堆容量是2,此刻已经满了, 后面要进来的数得过门槛才能进, 就是次数比堆顶的多, 堆顶的就是此时堆中出现次数最少的那个, 我秒掉最差我就能进来 所以这也是为什么要小根堆的原因

image.png
image.png

时间复杂度分析 建好计账表O(N) 堆大小K 一条记录进堆,调整的代价是logK 所以整体的时间复杂度O(N * logK)

  1. public class Node {
  2. int num;
  3. int count;
  4. public Node(int num) {
  5. this.num = num;
  6. this.count = 1;
  7. }
  8. }
  9. public int[] topKFrequent(int[] nums, int k) {
  10. int[] result = new int[k];
  11. // map统计词频
  12. HashMap<Integer, Node> map = new HashMap<>();
  13. for (int num : nums) {
  14. if (!map.containsKey(num)) {
  15. map.put(num, new Node(num));
  16. } else {
  17. map.get(num).count++;
  18. }
  19. }
  20. // 小顶堆
  21. PriorityQueue<Node> minHeap = new PriorityQueue<>((o1, o2) -> o1.count - o2.count );
  22. for (Node node : map.values()) {
  23. if (minHeap.size() < k || minHeap.size() == k && node.count > minHeap.peek().count) {
  24. minHeap.add(node);
  25. }
  26. if (minHeap.size() > k) {
  27. minHeap.poll();
  28. }
  29. }
  30. for (int i = 0; i < k; i++) {
  31. result[i] = minHeap.poll().num;
  32. }
  33. return result;
  34. }