Question
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]
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
public int[] topKFrequent(int[] nums, int k) { if (nums.length == 0 || k > nums.length) { return new int[] {}; } Map<Integer, Integer> map = new HashMap<>(); PriorityQueue<Integer> heap = new PriorityQueue<>((o1,o2) -> map.get(o1)-map.get(o2)); for (int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0)+1); } for (int n : map.keySet()) { heap.offer(n); if (heap.size() > k) { heap.poll(); } } int[] res = new int[heap.size()]; int i = 0; for (int n : heap) { res[i++] = n; } return res; }
|