From 60c3a27ce9537d7361e4927b21129bf77be507ba Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Mon, 24 Jan 2022 17:39:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880347.=E5=89=8DK?= =?UTF-8?q?=E4=B8=AA=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0.md=EF=BC=89?= =?UTF-8?q?=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 8bd774e9..1d6a358b 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -358,6 +358,22 @@ PriorityQueue.prototype.compare = function(index1, index2) { } ``` +TypeScript: + +```typescript +function topKFrequent(nums: number[], k: number): number[] { + const countMap: Map = 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]); +}; +``` + -----------------------