43
43
44
44
<!-- 这里可写通用的实现逻辑 -->
45
45
46
- 经典 Top K 问题,可以用堆解决
46
+ ** 方法一:哈希表 + 优先队列(小根堆)**
47
+
48
+ 使用哈希表统计每个元素出现的次数,然后使用优先队列(小根堆)维护前 $k$ 个出现次数最多的元素。
49
+
50
+ 时间复杂度 $O(n\log k)$。
47
51
48
52
<!-- tabs:start -->
49
53
54
58
``` python
55
59
class Solution :
56
60
def topKFrequent (self , nums : List[int ], k : int ) -> List[int ]:
57
- counter = Counter(nums)
61
+ cnt = Counter(nums)
62
+ return [v[0 ] for v in cnt.most_common(k)]
63
+ ```
64
+
65
+ ``` python
66
+ class Solution :
67
+ def topKFrequent (self , nums : List[int ], k : int ) -> List[int ]:
68
+ cnt = Counter(nums)
58
69
hp = []
59
- for num, freq in counter .items():
60
- if len (hp) == k:
61
- heappush (hp, (freq, num))
70
+ for num, freq in cnt .items():
71
+ heappush (hp, (freq, num))
72
+ if len (hp) > k:
62
73
heappop(hp)
63
- else :
64
- heappush(hp, (freq, num))
65
- return [t[1 ] for t in hp]
74
+ return [v[1 ] for v in hp]
66
75
```
67
76
68
77
### ** Java**
@@ -72,22 +81,15 @@ class Solution:
72
81
``` java
73
82
class Solution {
74
83
public int [] topKFrequent (int [] nums , int k ) {
75
- Map<Integer , Long > frequency = Arrays . stream(nums). boxed()
76
- .collect(Collectors . groupingBy(Function . identity(), Collectors . counting()));
77
-
84
+ Map<Integer , Long > frequency = Arrays . stream(nums). boxed(). collect(
85
+ Collectors . groupingBy(Function . identity(), Collectors . counting()));
78
86
Queue<Map .Entry<Integer , Long > > queue = new PriorityQueue<> (Map . Entry . comparingByValue());
79
- for (Map . Entry<Integer , Long > entry : frequency. entrySet()) {
80
- long count = entry. getValue();
81
- if (queue. size() == k) {
82
- if (count > queue. peek(). getValue()) {
83
- queue. poll();
84
- queue. offer(entry);
85
- }
86
- } else {
87
- queue. offer(entry);
87
+ for (var entry : frequency. entrySet()) {
88
+ queue. offer(entry);
89
+ if (queue. size() > k) {
90
+ queue. poll();
88
91
}
89
92
}
90
-
91
93
return queue. stream(). mapToInt(Map . Entry :: getKey). toArray();
92
94
}
93
95
}
@@ -96,53 +98,159 @@ class Solution {
96
98
``` java
97
99
class Solution {
98
100
public int [] topKFrequent (int [] nums , int k ) {
99
- Map<Integer , Integer > counter = new HashMap<> ();
100
- for (int num : nums) {
101
- counter . put(num, counter . getOrDefault(num , 0 ) + 1 );
101
+ Map<Integer , Integer > cnt = new HashMap<> ();
102
+ for (int v : nums) {
103
+ cnt . put(v, cnt . getOrDefault(v , 0 ) + 1 );
102
104
}
103
- PriorityQueue<int[]> pq = new PriorityQueue<> (Comparator . comparingInt(a - > a[1 ]) );
104
- counter . forEach((num, freq) - > {
105
- if ( pq. size() == k) {
106
- pq. offer( new int [] {num, freq});
105
+ PriorityQueue<int[]> pq = new PriorityQueue<> ((a, b) - > a[1 ] - b[ 1 ] );
106
+ for ( var e : cnt . entrySet()) {
107
+ pq. offer( new int [] {e . getKey(), e . getValue()});
108
+ if ( pq. size() > k) {
107
109
pq. poll();
108
- } else {
109
- pq. offer(new int [] {num, freq});
110
110
}
111
- });
112
- return pq. stream(). mapToInt(e - > e[0 ]). toArray();
111
+ }
112
+ int [] ans = new int [k];
113
+ for (int i = 0 ; i < k; ++ i) {
114
+ ans[i] = pq. poll()[0 ];
115
+ }
116
+ return ans;
113
117
}
114
118
}
115
119
```
116
120
121
+ ### ** TypeScript**
122
+
123
+ ``` ts
124
+ function topKFrequent(nums : number [], k : number ): number [] {
125
+ let hashMap = new Map ();
126
+ for (let num of nums ) {
127
+ hashMap .set (num , (hashMap .get (num ) || 0 ) + 1 );
128
+ }
129
+ let list = [... hashMap ];
130
+ list .sort ((a , b ) => b [1 ] - a [1 ]);
131
+ let ans = [];
132
+ for (let i = 0 ; i < k ; i ++ ) {
133
+ ans .push (list [i ][0 ]);
134
+ }
135
+ return ans ;
136
+ }
137
+ ```
138
+
139
+ ``` ts
140
+ function topKFrequent(nums : number [], k : number ): number [] {
141
+ const map = new Map <number , number >();
142
+ let maxCount = 0 ;
143
+ for (const num of nums ) {
144
+ map .set (num , (map .get (num ) ?? 0 ) + 1 );
145
+ maxCount = Math .max (maxCount , map .get (num ));
146
+ }
147
+
148
+ const res = [];
149
+ while (k > 0 ) {
150
+ for (const key of map .keys ()) {
151
+ if (map .get (key ) === maxCount ) {
152
+ res .push (key );
153
+ k -- ;
154
+ }
155
+ }
156
+ maxCount -- ;
157
+ }
158
+ return res ;
159
+ }
160
+ ```
161
+
117
162
### ** C++**
118
163
119
164
``` cpp
165
+ using pii = pair<int , int >;
166
+
120
167
class Solution {
121
168
public:
122
- static bool cmp(pair<int, int>& m, pair<int, int>& n) {
123
- return m.second > n.second;
124
- }
125
169
vector<int > topKFrequent(vector<int >& nums, int k) {
126
- unordered_map<int, int> counter ;
127
- for (auto& e : nums) ++counter [ e ] ;
128
- priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq(cmp) ;
129
- for (auto& [ num, freq] : counter ) {
130
- if ( pq.size() == k) {
131
- pq.emplace(num, freq);
170
+ unordered_map<int, int> cnt ;
171
+ for (int v : nums) ++cnt [ v ] ;
172
+ priority_queue<pii, vector<pii >, greater< pii >> pq ;
173
+ for (auto& [ num, freq] : cnt ) {
174
+ pq.push({freq, num});
175
+ if ( pq.size() > k) {
132
176
pq.pop();
133
- } else
134
- pq.emplace(num, freq);
177
+ }
135
178
}
136
- vector<int > ans;
137
- while (!pq.empty() ) {
138
- ans.push_back( pq.top().first) ;
179
+ vector<int > ans(k) ;
180
+ for (int i = 0; i < k; ++i ) {
181
+ ans[ i ] = pq.top().second ;
139
182
pq.pop();
140
183
}
141
184
return ans;
142
185
}
143
186
};
144
187
```
145
188
189
+ ### **Go**
190
+
191
+ ```go
192
+ func topKFrequent(nums []int, k int) []int {
193
+ cnt := map[int]int{}
194
+ for _, v := range nums {
195
+ cnt[v]++
196
+ }
197
+ h := hp{}
198
+ for v, freq := range cnt {
199
+ heap.Push(&h, pair{v, freq})
200
+ if len(h) > k {
201
+ heap.Pop(&h)
202
+ }
203
+ }
204
+ ans := make([]int, k)
205
+ for i := range ans {
206
+ ans[i] = heap.Pop(&h).(pair).v
207
+ }
208
+ return ans
209
+ }
210
+
211
+ type pair struct{ v, cnt int }
212
+ type hp []pair
213
+
214
+ func (h hp) Len() int { return len(h) }
215
+ func (h hp) Less(i, j int) bool { return h[i].cnt < h[j].cnt }
216
+ func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
217
+ func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
218
+ func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
219
+ ```
220
+
221
+ ### ** Rust**
222
+
223
+ ``` rust
224
+ use std :: collections :: HashMap ;
225
+ impl Solution {
226
+ pub fn top_k_frequent (nums : Vec <i32 >, k : i32 ) -> Vec <i32 > {
227
+ let mut map = HashMap :: new ();
228
+ let mut max_count = 0 ;
229
+ for & num in nums . iter () {
230
+ let val = map . get (& num ). unwrap_or (& 0 ) + 1 ;
231
+ map . insert (num , val );
232
+ max_count = max_count . max (val );
233
+ }
234
+ let mut k = k as usize ;
235
+ let mut res = vec! [0 ; k ];
236
+ while k > 0 {
237
+ let mut next = 0 ;
238
+ for key in map . keys () {
239
+ let val = map [key ];
240
+ if val == max_count {
241
+ res [k - 1 ] = * key ;
242
+ k -= 1 ;
243
+ } else if val < max_count {
244
+ next = next . max (val );
245
+ }
246
+ }
247
+ max_count = next ;
248
+ }
249
+ res
250
+ }
251
+ }
252
+ ```
253
+
146
254
### ** ...**
147
255
148
256
```
0 commit comments