1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
var topKFrequent = function (nums, k) { const map = new Map(); for (const num of nums) { map.set(num, (map.get(num) || 0) + 1); } const heap = []; for (const [num, freq] of map.entries()) { if (heap.length < k) { heap.push([num, freq]); heap.sort((a, b) => a[1] - b[1]); } else if (freq > heap[0][1]) { heap[0] = [num, freq]; heap.sort((a, b) => a[1] - b[1]); } } return heap.map((pair) => pair[0]); };
|