347. Top K Frequent Elements

题目

Given a non-empty array of integers, return the *k* most frequent elements.

示例1:

1
2
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

示例2:

1
2
Input: nums = [1], k = 1
Output: [1]

提示:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

解法

解法一:

构造一个大顶堆,取K个即可。

JAVA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Node {
private int value;

private int count;

public Node(int value, int count) {
this.value = value;
this.count = count;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}
}

public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> values = new HashMap<Integer, Integer>();

for (int num : nums) {
if (values.containsKey(num)) {
values.put(num, values.get(num) + 1);
} else {
values.put(num, 1);
}
}

PriorityQueue<Node> nodes = new PriorityQueue<>(values.size(), (a, b) -> b.getCount() - a.getCount());
for (Map.Entry<Integer, Integer> entry : values.entrySet()) {
Node node = new Node(entry.getKey(), entry.getValue());
nodes.add(node);
}

List<Integer> result = new ArrayList<Integer>(k);
while (k > 0 && !nodes.isEmpty()) {
result.add(nodes.poll().getValue());
k--;
}

return result;
}
0%