Q:
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.
如果nums[i]不存在于HashMap中,则将nums[i]作为key,1作为value(代表第一次出现).
否则将nums[i]对应的value++.
然后将map存入list<Entry>中,以value降序排序,最后获取top k个entry即可.
public List<Integer> topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
int i = 0, length = nums.length;
while (i < length) {
int num = nums[i++];
Integer count = map.get(num);
if (count == null) {
map.put(num, 1);
} else {
map.put(num, count + 1);
}
}
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
List<Entry<Integer, Integer>> listToBeSorted = new ArrayList<>(entrySet);
Collections.sort(listToBeSorted, new Comparator<Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> e1, Entry<Integer, Integer> e2) {
return e2.getValue() - e1.getValue();
}
});
List<Integer> resultList = new ArrayList<>(listToBeSorted.size());
for (Entry<Integer, Integer> entry : listToBeSorted) {
if (k-- <= 0) {
break;
}
resultList.add(entry.getKey());
}
return resultList;
}