21 March 2024
Medium
347. Top K Frequent Elements
Link: https://leetcode.com/problems/top-k-frequent-elements
Description: We need to find k most frequent elements in array.
Solution:
Create object and count how many times each number appears in array. Then sort object by values and return first k keys.
var topKFrequent = function (nums, k) {
const obj = {}
for (const n of nums) {
if (obj[n] !== undefined) {
obj[n] += 1
continue
}
obj[n] = 1
}
const sorted = Object.entries(obj).sort((a, b) => {
if (a[1] < b[1]) {
return 1
} else {
return -1
}
})
return sorted.slice(0, k).map((el) => +el[0])
}