Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
class Solution { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (Integer num: nums) { map.put(num, map.getOrDefault(num, 0) + 1); } // keep a top frequency heap PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()): a.getValue() - b.getValue() ); for (Map.Entry<Integer, Integer> entry: map.entrySet()) { pq.offer(entry); if (pq.size() > k) { pq.poll(); } } List<Integer> res = new ArrayList<>(); // while (!pq.isEmpty()) { // res.add(0, pq.poll().getKey()); // } while (!pq.isEmpty()) { res.add(pq.poll().getKey()); } return res; } }
原文地址:https://www.cnblogs.com/xuanlu/p/12315324.html
时间: 2024-10-08 00:55:59