Skip to content

Commit 0d3a2af

Browse files
committed
feat: update ts solution to lc problem No.0347
1 parent 43a0d90 commit 0d3a2af

File tree

3 files changed

+24
-30
lines changed

3 files changed

+24
-30
lines changed

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

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -159,17 +159,15 @@ func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1];
159159

160160
```ts
161161
function topKFrequent(nums: number[], k: number): number[] {
162-
let hashMap = new Map();
163-
for (let num of nums) {
164-
hashMap.set(num, (hashMap.get(num) || 0) + 1);
165-
}
166-
let list = [...hashMap];
167-
list.sort((a, b) => b[1] - a[1]);
168-
let ans = [];
169-
for (let i = 0; i < k; i++) {
170-
ans.push(list[i][0]);
162+
const cnt = new Map();
163+
for (const num of nums) {
164+
cnt.set(num, (cnt.get(num) || 0) + 1);
171165
}
172-
return ans;
166+
167+
return [...cnt]
168+
.sort((a, b) => b[1] - a[1])
169+
.splice(0, k)
170+
.map(([x]) => x);
173171
}
174172
```
175173

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

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,15 @@ func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1];
147147

148148
```ts
149149
function topKFrequent(nums: number[], k: number): number[] {
150-
let hashMap = new Map();
151-
for (let num of nums) {
152-
hashMap.set(num, (hashMap.get(num) || 0) + 1);
153-
}
154-
let list = [...hashMap];
155-
list.sort((a, b) => b[1] - a[1]);
156-
let ans = [];
157-
for (let i = 0; i < k; i++) {
158-
ans.push(list[i][0]);
150+
const cnt = new Map();
151+
for (const num of nums) {
152+
cnt.set(num, (cnt.get(num) || 0) + 1);
159153
}
160-
return ans;
154+
155+
return [...cnt]
156+
.sort((a, b) => b[1] - a[1])
157+
.splice(0, k)
158+
.map(([x]) => x);
161159
}
162160
```
163161

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
function topKFrequent(nums: number[], k: number): number[] {
2-
let hashMap = new Map();
3-
for (let num of nums) {
4-
hashMap.set(num, (hashMap.get(num) || 0) + 1);
2+
const cnt = new Map();
3+
for (const num of nums) {
4+
cnt.set(num, (cnt.get(num) || 0) + 1);
55
}
6-
let list = [...hashMap];
7-
list.sort((a, b) => b[1] - a[1]);
8-
let ans = [];
9-
for (let i = 0; i < k; i++) {
10-
ans.push(list[i][0]);
11-
}
12-
return ans;
6+
7+
return [...cnt]
8+
.sort((a, b) => b[1] - a[1])
9+
.splice(0, k)
10+
.map(([x]) => x);
1311
}

0 commit comments

Comments
 (0)