forked from surajr/CodingInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopKFrequent.java
More file actions
26 lines (22 loc) · 779 Bytes
/
topKFrequent.java
File metadata and controls
26 lines (22 loc) · 779 Bytes
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
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] bucket = new List[nums.length+1];
HashMap<Integer, Integer> map = new HashMap<>();
for(int num:nums)
map.put(num, map.getOrDefault(num,0)+1);
for(int key:map.keySet())
{
int freq = map.get(key);
if(bucket[freq] == null)
bucket[freq] = new LinkedList<>();
bucket[freq].add(key);
}
List<Integer> result = new LinkedList<>();
for(int pos = bucket.length-1; pos >= 0 && result.size() < k; pos--)
{
if(bucket[pos] != null)
result.addAll(bucket[pos]);
}
return result;
}
}