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; } }
public class Solution { public String[] topKFrequent(String[] combo, int k) { // Write your solution here. Map<String, Integer> map = new HashMap<>(); for (String s: combo) { map.put(s, map.getOrDefault(s, 0) + 1); } PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(k, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) { return a.getValue().compareTo(b.getValue()); } }); for (Map.Entry<String, Integer> mymap: map.entrySet()) { pq.offer(mymap); if (pq.size() > k) { pq.poll(); } } String[] res = new String[pq.size()]; for (int i = res.length - 1; i >= 0; i--) { res[i] = pq.poll().getKey(); } return res; } }