Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
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.
思路:通过可保存映射关系的map,将每个值及其出现次数保存下来,然后就是对entry排序的问题,在这道题中是按值排序。
为了使用Collection的sort方法,先将entrySet转化为List,然后重写了Comparator接口的compare方法,取降序排序后的前k项就是我们要的结果。
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer,Integer> count = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(count.containsKey(nums[i])) count.put(nums[i], count.get(nums[i])+1);
else count.put(nums[i],1);
}
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(count.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
//降序排序
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<k;i++){
result.add(list.get(i).getKey());
}
return result;
}
}