mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1056 from xiaofei-2020/stack8
添加(0347.前K个高频元素.md):增加typescript版本
This commit is contained in:
@ -358,6 +358,22 @@ PriorityQueue.prototype.compare = function(index1, index2) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
TypeScript:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function topKFrequent(nums: number[], k: number): number[] {
|
||||||
|
const countMap: Map<number, number> = new Map();
|
||||||
|
for (let num of nums) {
|
||||||
|
countMap.set(num, (countMap.get(num) || 0) + 1);
|
||||||
|
}
|
||||||
|
// tS没有最小堆的数据结构,所以直接对整个数组进行排序,取前k个元素
|
||||||
|
return [...countMap.entries()]
|
||||||
|
.sort((a, b) => b[1] - a[1])
|
||||||
|
.slice(0, k)
|
||||||
|
.map(i => i[0]);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user