- A loop is run to go through each number.
- A map is used to check if the number is seen for the first time , if it has not been then the loop skips to the next number.
- if a number is seen for the first time a second inner loop is run to check which other number in the array is the same as the current number.
- the map is turned into an array of arrays and the
knumber frequent elements which are thei[0]values are returned.
-
Time complexity:O(N^2)
-
Space complexity:O(N)
function topKFrequent(nums: number[], k: number): number[] {
let n = nums.length
let result: number[] = []
let seen = new Map()
for (let i = 0; i < n; i++) {
let j = 0
let size = 0
if (seen.has(nums[i])) continue
while (j < n) {
if (nums[i] === nums[j]) {
size++
}
j++
}
seen.set(nums[i],size)
}
let sorted = [...seen.entries()].sort((a, b) => b[1] - a[1])
return sorted.slice(0, k).map(entry => entry[0])
};