您的位置:首页 > 产品设计 > UI/UE

Leetcode题解 347. Top K Frequent Elements

2016-07-20 16:03 423 查看
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].

用桶排序来做最后处理。

public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {

//step1—用哈希表统计数组中各元素出现的频次,表中“键”为元素数值,“值”为对应元素出现的频次
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int num:nums)//遍历数组
{
if(map.get(num)==null)//如果“键”为num的数据首次出现,则“值”设为1
map.put(num, 1);
else
map.put(num, map.get(num)+1);//重复出现,则累计频次
}

List<Integer>[] list=new ArrayList[nums.length+1];
for(int key:map.keySet()){
int count=map.get(key);
if(list[count]==null)
list[count]=new ArrayList();
list[count].add(key);
}
List<Integer> result=new ArrayList();

for(int i=nums.length;i>=0;i--){
if(list[i]!=null&&result.size()<k){
result.addAll(list[i]);
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode