|
| 1 | + |
| 2 | +/** |
| 3 | + * @param {number[]} nums |
| 4 | + * @param {number} k |
| 5 | + * @return {number[]} |
| 6 | + */ |
| 7 | +const topKFrequent = (nums, k) => { |
| 8 | + // [1,1,1,2,2,3] |
| 9 | + if (k < 1) return []; |
| 10 | + |
| 11 | + // a map of the appear nb, a list of nums length to store the list based on appr nb |
| 12 | + let map = new Map(), kList = Array.from({ length: nums.length + 1}, () => []); |
| 13 | + // Array(nums.length).fill([]); - This will fill the array with empty arrays but it has the same references to each item (array). |
| 14 | + // you are actually pushing values into the same array instance across all indices. |
| 15 | + |
| 16 | + |
| 17 | + // process the map |
| 18 | + for (let i = 0; i < nums.length; i++) { |
| 19 | + map.set(nums[i], (map.get(nums[i]) || 0) + 1) |
| 20 | + } |
| 21 | + |
| 22 | + // i will have a k list then to get from behind, (pop) if empty, nth, otherwise, K--; ⇒ 0 |
| 23 | + // [[], …] |
| 24 | + console.log(map) |
| 25 | + console.log(kList) |
| 26 | + for (let [key, value] of map) { |
| 27 | + console.log(value) |
| 28 | + console.log(kList[value]) |
| 29 | + kList[value].push(key); |
| 30 | + console.log("kList") |
| 31 | + console.log(kList) |
| 32 | + } |
| 33 | + |
| 34 | + // [[],[3],[2],[1], …] |
| 35 | + let result = [], tmpK = k; |
| 36 | + |
| 37 | + while (tmpK > 0) { |
| 38 | + let curr = kList.pop(); |
| 39 | + if (0 < curr.length) { |
| 40 | + result.push(curr); |
| 41 | + tmpK -= curr.length; |
| 42 | + } |
| 43 | + } |
| 44 | + // [[1,2], [3]] |
| 45 | + |
| 46 | + |
| 47 | + console.log("result") |
| 48 | + console.log(k) |
| 49 | + console.log(result.flat()) |
| 50 | + console.log(result.flat().slice(0, k)) |
| 51 | + |
| 52 | + return result.flat().slice(0, k); |
| 53 | +} |
| 54 | +// topKFrequent([1, 1, 1, 2, 2, 2, 3], 2) |
| 55 | +// topKFrequent([1], 1) |
| 56 | +// topKFrequent([1,2], 2) |
0 commit comments