-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path347-Top-K-Frequent-Elements.js
More file actions
37 lines (34 loc) · 983 Bytes
/
347-Top-K-Frequent-Elements.js
File metadata and controls
37 lines (34 loc) · 983 Bytes
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
/**
* https://leetcode.com/problems/top-k-frequent-elements/description/
* Difficulty:Medium
*
* Given a non-empty array of integers, return the k most frequent elements.
*
* For example,
* Given [1,1,1,2,2,3] and k = 2, return [1,2].
*
* Note:
* You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
* Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
*
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function (nums, k) {
var map = {};
for (var i = 0; i < nums.length; i++) {
map[nums[i]] = map[nums[i]] ? map[nums[i]] + 1 : 1;
}
var keys = Object.keys(map);
keys.sort((a, b) => {
if (map[a] > map[b]) return -1;
if (map[a] < map[b]) return 1;
return 0;
});
// console.log(map, keys);
return keys.slice(0, k).map(a => parseInt(a));
};
console.log(topKFrequent([1, 1, 1, 2, 2, 3, 4], 2));