Skip to content

Commit 9b6cfd7

Browse files
committed
feat: update solutions to lc/lcof2 problems
* Top K Frequent Elements
1 parent 427d1f0 commit 9b6cfd7

File tree

8 files changed

+245
-80
lines changed

8 files changed

+245
-80
lines changed

lcof2/剑指 Offer II 060. 出现频率最高的 k 个数字/README.md

Lines changed: 154 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,11 @@
4343

4444
<!-- 这里可写通用的实现逻辑 -->
4545

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

4852
<!-- tabs:start -->
4953

@@ -54,15 +58,20 @@
5458
```python
5559
class Solution:
5660
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)
5869
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:
6273
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]
6675
```
6776

6877
### **Java**
@@ -72,22 +81,15 @@ class Solution:
7281
```java
7382
class Solution {
7483
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()));
7886
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();
8891
}
8992
}
90-
9193
return queue.stream().mapToInt(Map.Entry::getKey).toArray();
9294
}
9395
}
@@ -96,53 +98,159 @@ class Solution {
9698
```java
9799
class Solution {
98100
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);
102104
}
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) {
107109
pq.poll();
108-
} else {
109-
pq.offer(new int[] {num, freq});
110110
}
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;
113117
}
114118
}
115119
```
116120

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+
117162
### **C++**
118163

119164
```cpp
165+
using pii = pair<int, int>;
166+
120167
class Solution {
121168
public:
122-
static bool cmp(pair<int, int>& m, pair<int, int>& n) {
123-
return m.second > n.second;
124-
}
125169
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) {
132176
pq.pop();
133-
} else
134-
pq.emplace(num, freq);
177+
}
135178
}
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;
139182
pq.pop();
140183
}
141184
return ans;
142185
}
143186
};
144187
```
145188
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+
146254
### **...**
147255

148256
```

lcof2/剑指 Offer II 060. 出现频率最高的 k 个数字/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;
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
func topKFrequent(nums []int, k int) []int {
2+
cnt := map[int]int{}
3+
for _, v := range nums {
4+
cnt[v]++
5+
}
6+
h := hp{}
7+
for v, freq := range cnt {
8+
heap.Push(&h, pair{v, freq})
9+
if len(h) > k {
10+
heap.Pop(&h)
11+
}
12+
}
13+
ans := make([]int, k)
14+
for i := range ans {
15+
ans[i] = heap.Pop(&h).(pair).v
16+
}
17+
return ans
18+
}
19+
20+
type pair struct{ v, cnt int }
21+
type hp []pair
22+
23+
func (h hp) Len() int { return len(h) }
24+
func (h hp) Less(i, j int) bool { return h[i].cnt < h[j].cnt }
25+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
26+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
27+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }

lcof2/剑指 Offer II 060. 出现频率最高的 k 个数字/Solution.java

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,13 @@ class Solution {
22
public int[] topKFrequent(int[] nums, int k) {
33
Map<Integer, Long> frequency = Arrays.stream(nums).boxed().collect(
44
Collectors.groupingBy(Function.identity(), Collectors.counting()));
5-
65
Queue<Map.Entry<Integer, Long>> queue = new PriorityQueue<>(Map.Entry.comparingByValue());
7-
for (Map.Entry<Integer, Long> entry : frequency.entrySet()) {
8-
long count = entry.getValue();
9-
if (queue.size() == k) {
10-
if (count > queue.peek().getValue()) {
11-
queue.poll();
12-
queue.offer(entry);
13-
}
14-
} else {
15-
queue.offer(entry);
6+
for (var entry : frequency.entrySet()) {
7+
queue.offer(entry);
8+
if (queue.size() > k) {
9+
queue.poll();
1610
}
1711
}
18-
1912
return queue.stream().mapToInt(Map.Entry::getKey).toArray();
2013
}
2114
}
Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
class Solution:
22
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
3-
counter = Counter(nums)
3+
cnt = Counter(nums)
44
hp = []
5-
for num, freq in counter.items():
6-
if len(hp) == k:
7-
heappush(hp, (freq, num))
5+
for num, freq in cnt.items():
6+
heappush(hp, (freq, num))
7+
if len(hp) > k:
88
heappop(hp)
9-
else:
10-
heappush(hp, (freq, num))
11-
return [t[1] for t in hp]
9+
return [v[1] for v in hp]
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use std::collections::HashMap;
2+
impl Solution {
3+
pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
4+
let mut map = HashMap::new();
5+
let mut max_count = 0;
6+
for &num in nums.iter() {
7+
let val = map.get(&num).unwrap_or(&0) + 1;
8+
map.insert(num, val);
9+
max_count = max_count.max(val);
10+
}
11+
let mut k = k as usize;
12+
let mut res = vec![0; k];
13+
while k > 0 {
14+
let mut next = 0;
15+
for key in map.keys() {
16+
let val = map[key];
17+
if val == max_count {
18+
res[k - 1] = *key;
19+
k -= 1;
20+
} else if val < max_count {
21+
next = next.max(val);
22+
}
23+
}
24+
max_count = next;
25+
}
26+
res
27+
}
28+
}

0 commit comments

Comments
 (0)