-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopKElementsInList.js
More file actions
91 lines (71 loc) · 2.25 KB
/
TopKElementsInList.js
File metadata and controls
91 lines (71 loc) · 2.25 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Top K Elements in List
// Given an integer array nums and an integer k, return the k most frequent elements within the array.
// The test cases are generated such that the answer is always unique.
// You may return the output in any order.
// Example 1:
// Input: nums = [1,2,2,3,3,3], k = 2
// Output: [2,3]
// Example 2:
// Input: nums = [7,7], k = 1
// Output: [7]
// Constraints:
// 1 <= nums.length <= 10^4.
// -1000 <= nums[i] <= 1000
// 1 <= k <= number of distinct elements in nums.
class Solution {
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
topKFrequent(nums, k) {
const frequencyMap = new Map();
// Count the frequency of each element
for (let num of nums) {
frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);
}
// Create an array of the elements sorted by frequency
let frequencyMapKeys = frequencyMap.keys();
const sortedElements = Array.from(frequencyMapKeys).sort((a, b) => frequencyMap.get(b) - frequencyMap.get(a));
// Return the first k elements
return sortedElements.slice(0, k);
}
}
// class Solution {
// /**
// * @param {number[]} nums
// * @param {number} k
// * @return {number[]}
// */
// topKFrequent(nums, k) {
// const count = {};
// const freq = Array.from({ length: nums.length + 1 }, () => []);
// for (const n of nums) {
// count[n] = (count[n] || 0) + 1;
// }
// for (const n in count) {
// let value = count[n];
// let property = parseInt(n);
// freq[value].push(property);
// }
// const res = [];
// for (let i = freq.length - 1; i > 0; i--) {
// for (const n of freq[i]) {
// res.push(n);
// if (res.length === k) {
// return res;
// }
// }
// }
// }
// }
// Example Usage:
const solution = new Solution();
// Example 1
let nums1 = [1, 2, 2, 3, 3, 3,1,1,5,7,7,7,];
let k1 = 2;
console.log(solution.topKFrequent(nums1, k1)); // Output: [3, 2]
// Example 2
let nums2 = [7, 7];
let k2 = 1;
console.log(solution.topKFrequent(nums2, k2)); // Output: [7]