Medium
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]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
if(nums==null || nums.length==0) return res;
HashMap<Integer,Integer> map = new HashMap<>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
ArrayList<Integer>[] arr = new ArrayList[nums.length+1];//wrong : new ArrayList<>[nums.length+1]
for(Integer key:map.keySet()){
int frequency = map.get(key);
if(arr[frequency]==null){
arr[frequency] = new ArrayList<Integer>();
}
arr[frequency].add(key);
}
for(int i=arr.length-1;i>=0&&res.size()<k;i--){
if(arr[i]==null)
continue;
if(arr[i].size()<k-res.size()){
res.addAll(arr[i]);
}
else{
res.addAll(arr[i].subList(0,k-res.size()));
}
}
return res;
}
}