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

leetcode题解-347. Top K Frequent Elements

2017-03-06 17:25 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].

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.

题目很简单,求出数组中出现频率最高的k个数即可。思路也很清晰,首先可以遍历出数组中所有数及其出现次数并将其保存在HashMap中。然后将map转化为以出现次数为索引,数为值的数组。最后再反向遍历出出现次数最大的k个数即可、代码入下,击败了70%多的用户:

public List<Integer> topKFrequent1(int[] nums, int k) {
int n = nums.length;
HashMap<Integer, Integer> h = new HashMap();
for (int i : nums)
if (h.containsKey(i))
h.put(i, h.get(i) + 1);
else
h.put(i, 1);

List<Integer>[] fc = new ArrayList[n + 1];
for (int i : h.keySet()) {
int f = h.get(i);       //System.out.println(f + " times of " + i);
if (fc[f] == null) fc[f] = new ArrayList();
fc[f].add(i);
}

List<Integer> ans = new ArrayList();
for (int i = n, j = 0; k > 0; k--) {
for (; fc[i] == null || j == fc[i].size(); j = 0, i--);
ans.add(fc[i].get(j++));
}

return ans;
}


此外还可以使用优先级队列和树等结构来完成此题,但因为使用较为复杂的数据结构,所以效果并不好。代码如下所示:

使用队列
public List<Integer> topKFrequent2(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();

for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
if (pq.size() < k) {
pq.offer(entry);
} else if (entry.getValue() > pq.peek().getValue()) {
pq.poll();
pq.offer(entry);
}
}

List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : pq) {
result.add(entry.getKey());
}

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