Skip to content

Commit 05e860e

Browse files
committed
refactor top-k-frequent-elements
1 parent def85b8 commit 05e860e

File tree

1 file changed

+3
-12
lines changed

1 file changed

+3
-12
lines changed

top-k-frequent-elements/jiji-hoon96.ts

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,13 @@
1212
*/
1313

1414
function topKFrequent(nums: number[], k: number): number[] {
15-
let result = []
1615
const countObject: { [key: number]: number } = {};
1716

1817
for(const num of nums){
19-
countObject[num] = (countObject[num] || 0) +1;
18+
countObject[num] = (countObject[num] || 0) + 1;
2019
}
2120

22-
const sortObject= Object.entries(countObject).sort((a,b) => b[1]- a[1]);
21+
const sortObject = Object.entries(countObject).sort((a,b) => b[1] - a[1]);
2322

24-
for(const [key] of sortObject){
25-
if(k>0){
26-
result.push(Number(key))
27-
k--;
28-
}
29-
30-
}
31-
32-
return result
23+
return sortObject.slice(0, k).map(([key]) => Number(key));
3324
};

0 commit comments

Comments
 (0)