[LeetCode] 347. Top K Frequent elements (javascript)
728x90
반응형
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function(nums, k) {
const map=new Map();
for(const num of nums){
if(!map.has(num)){
map.set(num,1)
}else{
map.set(num,map.get(num)+1);
}
}
const arr=[];
for(const [key,value] of map){
arr.push([key,value]);
}
arr.sort((a,b)=>b[1]-a[1]);
const answer=[];
for(let i=0;i<k;i++){
answer.push(arr[i][0]);
}
return answer;
};
728x90
반응형
'Leetcode' 카테고리의 다른 글
[LeetCode]3. Longest Substring without repeating characters (javascript) (0) | 2020.12.19 |
---|---|
[LeetCode] 771. Jewels and Stones (javascript) (0) | 2020.12.18 |
[LeetCode] 739. Daily Temperatures (javascript) (0) | 2020.12.18 |
[LeetCode] 316. Remove Duplicate letters (javascript) (0) | 2020.12.18 |
[LeetCode] 121. Best time to buy and sell stock (javascript) (0) | 2020.12.18 |
TAGS.