MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / topKFrequent

Method topKFrequent

java/0347-top-k-frequent-elements.java:7–24  ·  view source on GitHub ↗

Time Complexity: O(nlog(k)) Space Complexity: O(n)

(int[] nums, int k)

Source from the content-addressed store, hash-verified

5 * Space Complexity: O(n)
6 */
7 public int[] topKFrequent(int[] nums, int k) {
8 int[] arr = new int[k];
9 HashMap<Integer, Integer> map = new HashMap<>();
10 for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1);
11 PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(
12 (a, b) ->
13 a.getValue() - b.getValue()
14 );
15 for (Map.Entry<Integer, Integer> it : map.entrySet()) {
16 pq.add(it);
17 if (pq.size() > k) pq.poll();
18 }
19 int i = k;
20 while (!pq.isEmpty()) {
21 arr[--i] = pq.poll().getKey();
22 }
23 return arr;
24 }
25}
26
27class Solution2 {

Callers

nothing calls this directly

Calls 5

putMethod · 0.45
addMethod · 0.45
sizeMethod · 0.45
isEmptyMethod · 0.45
getKeyMethod · 0.45

Tested by

no test coverage detected