forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0347-top-k-frequent-elements.js
64 lines (57 loc) · 1.45 KB
/
0347-top-k-frequent-elements.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Set - Frequency Counter | Using sort
* Time O(NlogN) | Space O(N)
* https://leetcode.com/problems/top-k-frequent-elements/
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function(nums, k) {
let frequency = {}
for( let i = 0; i < nums.length; i++){
if(frequency.hasOwnProperty(nums[i])) frequency[nums[i]] += 1;
else frequency[nums[i]] = 1;
}
let result = Object.keys(frequency).map((key) => [Number(key), frequency[key]]);
let sortedResult = result.sort((a,b) => {
return b[1]-a[1]
})
let output = []
for ( let i = 0; i < k; i++){
output.push(sortedResult[i][0])
}
return output;
};
/**
* Without Sort
* Time O(N) | Space O(k)
* https://leetcode.com/problems/top-k-frequent-elements/
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function(nums, k) {
const mp = new Map();
const arr = new Array(nums.length + 1).fill(0);
const ans = [];
nums.forEach(el => {
const val = mp.get(el) || 0;
mp.set(el, val + 1);
});
for ( let [key, value] of mp ) {
const prev = arr[value] || [];
prev.push(key);
arr[value] = prev;
}
arr.reverse();
for (let el of arr) {
if (k < 1) break;
if (el) {
for (let el2 of el) {
ans.push(el2);
k--;
}
}
}
return ans;
};