347.前K个高频元素

1.题目描述:

  给定一个非空的整数数组,返回其中出现频率前 高的元素。

  题目链接:https://leetcode-cn.com/problems/top-k-frequent-elements/

2.解题思路及代码:

  利用哈希表存放数组元素及出现频率,利用一个大小为k的优先队列存放出现频率前K高的元素

  代码如下:

 

class Solution {
  public List<Integer> topKFrequent(int[] nums, int k) {
    HashMap<Integer, Integer> count = new HashMap();
    for (int n: nums) {
      count.put(n, count.getOrDefault(n, 0) + 1);
    }

    PriorityQueue<Integer> heap =new PriorityQueue<Integer>((n1, n2) -> count.get(n1) - count.get(n2));

    for (int n: count.keySet()) {
      heap.add(n);
      if (heap.size() > k)
        heap.poll();
    }

    List<Integer> top_k = new ArrayList();
    while (!heap.isEmpty())
      top_k.add(heap.poll());
    Collections.reverse(top_k);
    return top_k;
  }
}

猜你喜欢

转载自www.cnblogs.com/teensSpirit-code-life/p/11808356.html