Skip to content

Commit 556ec1e

Browse files
committed
feat: add solutions to lc problem: No.0347
No.0347.Top K Frequent Elements
1 parent bfa81dd commit 556ec1e

File tree

6 files changed

+203
-123
lines changed

6 files changed

+203
-123
lines changed

solution/0300-0399/0347.Top K Frequent Elements/README.md

Lines changed: 80 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,11 @@
4141

4242
<!-- 这里可写通用的实现逻辑 -->
4343

44-
经典 Top K 问题,可以用堆解决
44+
**方法一:哈希表 + 优先队列(大根堆)**
45+
46+
使用哈希表统计每个元素出现的次数,然后使用优先队列(大根堆)维护前 $k$ 个出现次数最多的元素。
47+
48+
时间复杂度 $O(n\log k)$。
4549

4650
<!-- tabs:start -->
4751

@@ -52,15 +56,20 @@
5256
```python
5357
class Solution:
5458
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
55-
counter = Counter(nums)
59+
cnt = Counter(nums)
60+
return [v[0] for v in cnt.most_common(k)]
61+
```
62+
63+
```python
64+
class Solution:
65+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
66+
cnt = Counter(nums)
5667
hp = []
57-
for num, freq in counter.items():
58-
if len(hp) == k:
59-
heappush(hp, (freq, num))
68+
for num, freq in cnt.items():
69+
heappush(hp, (freq, num))
70+
if len(hp) > k:
6071
heappop(hp)
61-
else:
62-
heappush(hp, (freq, num))
63-
return [t[1] for t in hp]
72+
return [v[1] for v in hp]
6473
```
6574

6675
### **Java**
@@ -70,22 +79,15 @@ class Solution:
7079
```java
7180
class Solution {
7281
public int[] topKFrequent(int[] nums, int k) {
73-
Map<Integer, Long> frequency = Arrays.stream(nums).boxed()
74-
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
75-
82+
Map<Integer, Long> frequency = Arrays.stream(nums).boxed().collect(
83+
Collectors.groupingBy(Function.identity(), Collectors.counting()));
7684
Queue<Map.Entry<Integer, Long>> queue = new PriorityQueue<>(Map.Entry.comparingByValue());
77-
for (Map.Entry<Integer, Long> entry : frequency.entrySet()) {
78-
long count = entry.getValue();
79-
if (queue.size() == k) {
80-
if (count > queue.peek().getValue()) {
81-
queue.poll();
82-
queue.offer(entry);
83-
}
84-
} else {
85-
queue.offer(entry);
85+
for (var entry : frequency.entrySet()) {
86+
queue.offer(entry);
87+
if (queue.size() > k) {
88+
queue.poll();
8689
}
8790
}
88-
8991
return queue.stream().mapToInt(Map.Entry::getKey).toArray();
9092
}
9193
}
@@ -94,20 +96,22 @@ class Solution {
9496
```java
9597
class Solution {
9698
public int[] topKFrequent(int[] nums, int k) {
97-
Map<Integer, Integer> counter = new HashMap<>();
98-
for (int num : nums) {
99-
counter.put(num, counter.getOrDefault(num, 0) + 1);
99+
Map<Integer, Integer> cnt = new HashMap<>();
100+
for (int v : nums) {
101+
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
100102
}
101-
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
102-
counter.forEach((num, freq) -> {
103-
if (pq.size() == k) {
104-
pq.offer(new int[] {num, freq});
103+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
104+
for (var e : cnt.entrySet()) {
105+
pq.offer(new int[] {e.getKey(), e.getValue()});
106+
if (pq.size() > k) {
105107
pq.poll();
106-
} else {
107-
pq.offer(new int[] {num, freq});
108108
}
109-
});
110-
return pq.stream().mapToInt(e -> e[0]).toArray();
109+
}
110+
int[] ans = new int[k];
111+
for (int i = 0; i < k; ++i) {
112+
ans[i] = pq.poll()[0];
113+
}
114+
return ans;
111115
}
112116
}
113117
```
@@ -156,32 +160,62 @@ function topKFrequent(nums: number[], k: number): number[] {
156160
### **C++**
157161

158162
```cpp
163+
using pii = pair<int, int>;
164+
159165
class Solution {
160166
public:
161-
static bool cmp(pair<int, int>& m, pair<int, int>& n) {
162-
return m.second > n.second;
163-
}
164167
vector<int> topKFrequent(vector<int>& nums, int k) {
165-
unordered_map<int, int> counter;
166-
for (auto& e : nums) ++counter[e];
167-
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp);
168-
for (auto& [num, freq] : counter) {
169-
if (pq.size() == k) {
170-
pq.emplace(num, freq);
168+
unordered_map<int, int> cnt;
169+
for (int v : nums) ++cnt[v];
170+
priority_queue<pii, vector<pii>, greater<pii>> pq;
171+
for (auto& [num, freq] : cnt) {
172+
pq.push({freq, num});
173+
if (pq.size() > k) {
171174
pq.pop();
172-
} else
173-
pq.emplace(num, freq);
175+
}
174176
}
175-
vector<int> ans;
176-
while (!pq.empty()) {
177-
ans.push_back(pq.top().first);
177+
vector<int> ans(k);
178+
for (int i = 0; i < k; ++i) {
179+
ans[i] = pq.top().second;
178180
pq.pop();
179181
}
180182
return ans;
181183
}
182184
};
183185
```
184186
187+
### **Go**
188+
189+
```go
190+
func topKFrequent(nums []int, k int) []int {
191+
cnt := map[int]int{}
192+
for _, v := range nums {
193+
cnt[v]++
194+
}
195+
h := hp{}
196+
for v, freq := range cnt {
197+
heap.Push(&h, pair{v, freq})
198+
if len(h) > k {
199+
heap.Pop(&h)
200+
}
201+
}
202+
ans := make([]int, k)
203+
for i := range ans {
204+
ans[i] = heap.Pop(&h).(pair).v
205+
}
206+
return ans
207+
}
208+
209+
type pair struct{ v, cnt int }
210+
type hp []pair
211+
212+
func (h hp) Len() int { return len(h) }
213+
func (h hp) Less(i, j int) bool { return h[i].cnt < h[j].cnt }
214+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
215+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
216+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
217+
```
218+
185219
### **Rust**
186220

187221
```rust

solution/0300-0399/0347.Top K Frequent Elements/README_EN.md

Lines changed: 75 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -36,38 +36,36 @@
3636
```python
3737
class Solution:
3838
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
39-
counter = Counter(nums)
39+
cnt = Counter(nums)
40+
return [v[0] for v in cnt.most_common(k)]
41+
```
42+
43+
```python
44+
class Solution:
45+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
46+
cnt = Counter(nums)
4047
hp = []
41-
for num, freq in counter.items():
42-
if len(hp) == k:
43-
heappush(hp, (freq, num))
48+
for num, freq in cnt.items():
49+
heappush(hp, (freq, num))
50+
if len(hp) > k:
4451
heappop(hp)
45-
else:
46-
heappush(hp, (freq, num))
47-
return [t[1] for t in hp]
52+
return [v[1] for v in hp]
4853
```
4954

5055
### **Java**
5156

5257
```java
5358
class Solution {
5459
public int[] topKFrequent(int[] nums, int k) {
55-
Map<Integer, Long> frequency = Arrays.stream(nums).boxed()
56-
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
57-
60+
Map<Integer, Long> frequency = Arrays.stream(nums).boxed().collect(
61+
Collectors.groupingBy(Function.identity(), Collectors.counting()));
5862
Queue<Map.Entry<Integer, Long>> queue = new PriorityQueue<>(Map.Entry.comparingByValue());
59-
for (Map.Entry<Integer, Long> entry : frequency.entrySet()) {
60-
long count = entry.getValue();
61-
if (queue.size() == k) {
62-
if (count > queue.peek().getValue()) {
63-
queue.poll();
64-
queue.offer(entry);
65-
}
66-
} else {
67-
queue.offer(entry);
63+
for (var entry : frequency.entrySet()) {
64+
queue.offer(entry);
65+
if (queue.size() > k) {
66+
queue.poll();
6867
}
6968
}
70-
7169
return queue.stream().mapToInt(Map.Entry::getKey).toArray();
7270
}
7371
}
@@ -76,20 +74,22 @@ class Solution {
7674
```java
7775
class Solution {
7876
public int[] topKFrequent(int[] nums, int k) {
79-
Map<Integer, Integer> counter = new HashMap<>();
80-
for (int num : nums) {
81-
counter.put(num, counter.getOrDefault(num, 0) + 1);
77+
Map<Integer, Integer> cnt = new HashMap<>();
78+
for (int v : nums) {
79+
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
8280
}
83-
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
84-
counter.forEach((num, freq) -> {
85-
if (pq.size() == k) {
86-
pq.offer(new int[] {num, freq});
81+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
82+
for (var e : cnt.entrySet()) {
83+
pq.offer(new int[] {e.getKey(), e.getValue()});
84+
if (pq.size() > k) {
8785
pq.poll();
88-
} else {
89-
pq.offer(new int[] {num, freq});
9086
}
91-
});
92-
return pq.stream().mapToInt(e -> e[0]).toArray();
87+
}
88+
int[] ans = new int[k];
89+
for (int i = 0; i < k; ++i) {
90+
ans[i] = pq.poll()[0];
91+
}
92+
return ans;
9393
}
9494
}
9595
```
@@ -138,32 +138,62 @@ function topKFrequent(nums: number[], k: number): number[] {
138138
### **C++**
139139

140140
```cpp
141+
using pii = pair<int, int>;
142+
141143
class Solution {
142144
public:
143-
static bool cmp(pair<int, int>& m, pair<int, int>& n) {
144-
return m.second > n.second;
145-
}
146145
vector<int> topKFrequent(vector<int>& nums, int k) {
147-
unordered_map<int, int> counter;
148-
for (auto& e : nums) ++counter[e];
149-
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp);
150-
for (auto& [num, freq] : counter) {
151-
if (pq.size() == k) {
152-
pq.emplace(num, freq);
146+
unordered_map<int, int> cnt;
147+
for (int v : nums) ++cnt[v];
148+
priority_queue<pii, vector<pii>, greater<pii>> pq;
149+
for (auto& [num, freq] : cnt) {
150+
pq.push({freq, num});
151+
if (pq.size() > k) {
153152
pq.pop();
154-
} else
155-
pq.emplace(num, freq);
153+
}
156154
}
157-
vector<int> ans;
158-
while (!pq.empty()) {
159-
ans.push_back(pq.top().first);
155+
vector<int> ans(k);
156+
for (int i = 0; i < k; ++i) {
157+
ans[i] = pq.top().second;
160158
pq.pop();
161159
}
162160
return ans;
163161
}
164162
};
165163
```
166164
165+
### **Go**
166+
167+
```go
168+
func topKFrequent(nums []int, k int) []int {
169+
cnt := map[int]int{}
170+
for _, v := range nums {
171+
cnt[v]++
172+
}
173+
h := hp{}
174+
for v, freq := range cnt {
175+
heap.Push(&h, pair{v, freq})
176+
if len(h) > k {
177+
heap.Pop(&h)
178+
}
179+
}
180+
ans := make([]int, k)
181+
for i := range ans {
182+
ans[i] = heap.Pop(&h).(pair).v
183+
}
184+
return ans
185+
}
186+
187+
type pair struct{ v, cnt int }
188+
type hp []pair
189+
190+
func (h hp) Len() int { return len(h) }
191+
func (h hp) Less(i, j int) bool { return h[i].cnt < h[j].cnt }
192+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
193+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
194+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
195+
```
196+
167197
### **Rust**
168198

169199
```rust

solution/0300-0399/0347.Top K Frequent Elements/Solution.cpp

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1+
using pii = pair<int, int>;
2+
13
class Solution {
24
public:
3-
static bool cmp(pair<int, int>& m, pair<int, int>& n) {
4-
return m.second > n.second;
5-
}
65
vector<int> topKFrequent(vector<int>& nums, int k) {
7-
unordered_map<int, int> counter;
8-
for (auto& e : nums) ++counter[e];
9-
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp);
10-
for (auto& [num, freq] : counter) {
11-
if (pq.size() == k) {
12-
pq.emplace(num, freq);
6+
unordered_map<int, int> cnt;
7+
for (int v : nums) ++cnt[v];
8+
priority_queue<pii, vector<pii>, greater<pii>> pq;
9+
for (auto& [num, freq] : cnt) {
10+
pq.push({freq, num});
11+
if (pq.size() > k) {
1312
pq.pop();
14-
} else
15-
pq.emplace(num, freq);
13+
}
1614
}
17-
vector<int> ans;
18-
while (!pq.empty()) {
19-
ans.push_back(pq.top().first);
15+
vector<int> ans(k);
16+
for (int i = 0; i < k; ++i) {
17+
ans[i] = pq.top().second;
2018
pq.pop();
2119
}
2220
return ans;

0 commit comments

Comments
 (0)