Created
October 20, 2022 02:05
-
-
Save RakhmedovRS/5864fdbe4fb2345781c94fda383a1b00 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public int[] topKFrequent(int[] nums, int k) { | |
| Map<Integer, Integer> valueToCount = new HashMap<>(); | |
| for (int num : nums) { | |
| int count = valueToCount.getOrDefault(num, 0) + 1; | |
| valueToCount.put(num, count); | |
| } | |
| int pos = 0; | |
| int[] answer = new int[k]; | |
| PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> | |
| valueToCount.get(b) - valueToCount.get(a)); | |
| pq.addAll(valueToCount.keySet()); | |
| while (k-- > 0) | |
| { | |
| answer[pos++] = pq.remove(); | |
| } | |
| return answer; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment