Skip to content

Instantly share code, notes, and snippets.

@RakhmedovRS
Created October 20, 2022 02:05
Show Gist options
  • Select an option

  • Save RakhmedovRS/5864fdbe4fb2345781c94fda383a1b00 to your computer and use it in GitHub Desktop.

Select an option

Save RakhmedovRS/5864fdbe4fb2345781c94fda383a1b00 to your computer and use it in GitHub Desktop.
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