class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
int[] re = new int[k];
List<Integer> list = new ArrayList<Integer>();
for(int shu: nums)
{
if(!map.containsKey(shu))
{
map.put(shu, 1);
}
else
{
map.put(shu,map.get(shu)+1);
}
}
Set<Integer> keySet = map.keySet();
Iterator<Integer> it = keySet.iterator();
while(it.hasNext())
{
Integer shu = it.next();
Integer cishu = map.get(shu);
System.out.println("shu:"+shu);
System.out.println("cishu:"+cishu);
list.add(cishu);
}
Collections.sort(list);
//list只存放频率前k高的元素次数
list = list.subList(list.size()-k,list.size());
System.out.println(" list:"+ list);
/*
遍历一遍map的次数,value,返回
re[0] = maplist.get(0)
*/
int len = list.size()-1;
int i = 0;
Iterator<Integer> it2 = keySet.iterator();
while(it2.hasNext() && k>0)
{
Integer shu = it2.next();
Integer cishu = map.get(shu);
System.out.println("shu:"+shu);
System.out.println("cishu:"+cishu);
//遍历map, key为数,value为对应的次数,如果次数存在List中,则加入最后的结果中
if(list.contains(cishu))
{
/*System.out.println("list.get(len-i):"+list.get(len-i));
System.out.println("xxshu:"+shu);
System.out.println("xxcishu:"+cishu);
*/
re[i] = shu;
i++;
k--;
}
}
return re;
}
}
官方:堆排序(优先级队列,先入先出)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
for (int num : nums) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}
// int[] 的第一个元素代表数组的值,第二个元素代表了该值出现的次数
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int num = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (queue.peek()[1] < count) {
queue.poll();
queue.offer(new int[]{num, count});
}
} else {
queue.offer(new int[]{num, count});
}
}
int[] ret = new int[k];
for (int i = 0; i < k; ++i) {
ret[i] = queue.poll()[0];
}
return ret;
}
}