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

LeetCode Top K Frequent Elements

2016-06-04 10:06 471 查看
题意:给出一个数组,求出前k个出现频率最多的数

思路:首先统计每个元素的次数(用Map),然后用堆排序只统计前k个(PriorityQueue)

代码如下:

class Solution
{
class Pair implements Comparable<Pair>
{
int key, value;

public int compareTo(Pair b)
{
return value - b.value;
}
}

public List<Integer> topKFrequent(int[] nums, int k)
{
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++)
{
if (map.containsKey(nums[i]))
{
map.put(nums[i], map.get(nums[i]) + 1);
}
else
{
map.put(nums[i], 1);
}
}

Comparator<Pair> cmp = new Comparator<Pair>()
{
public int compare(Pair a, Pair b)
{
return a.value - b.value;
}
};

Queue<Pair> queue = new PriorityQueue<Pair>(k, cmp);

for(Map.Entry<Integer, Integer> ele: map.entrySet())
{
Pair p = new Pair();
p.key = ele.getKey(); p.value = ele.getValue();

if (queue.size() < k)
{
queue.add(p);
}
else
{

if (p.compareTo(queue.peek()) > 0)
{
queue.poll();
queue.offer(p);
}
}
}

List<Integer> res = new ArrayList<Integer>();
while (!queue.isEmpty())
{
Pair p = queue.poll();
res.add(p.key);
}

Collections.sort(res);

return res;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: