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:
如果nums[i]不存在于HashMap中,则将nums[i]作为key,1作为value(代表第一次出现).
否则将nums[i]对应的value++.
然后将map存入list
public List topKFrequent(int[] nums, int k) {
HashMap 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> entrySet = map.entrySet();
List> listToBeSorted = new ArrayList<>(entrySet);
Collections.sort(listToBeSorted, new Comparator>() {
@Override
public int compare(Entry e1, Entry e2) {
return e2.getValue() - e1.getValue();
}
});
List resultList = new ArrayList<>(listToBeSorted.size());
for (Entry entry : listToBeSorted) {
if (k-- <= 0) {
break;
}
resultList.add(entry.getKey());
}
return resultList;
}