-
Notifications
You must be signed in to change notification settings - Fork 0
/
347-top-k-frequent-elements.js
66 lines (43 loc) · 1.66 KB
/
347-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
65
66
// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
// Example 1:
// Input: nums = [1,1,1,2,2,3], k = 2
// Output: [1,2]
// Example 2:
// Input: nums = [1], k = 1
// Output: [1]
//using map
function findKFrequentElements(nums, k) {
// Step 1: Count the frequency of each element
const frequencyMap = new Map();
nums.forEach(num => {
frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1);
});
// Step 2: Convert map entries to an array and sort it based on frequency
const sortedFrequencies = Array.from(frequencyMap.entries()).sort((a, b) => b[1] - a[1]);
debugger;
// Step 3: Extract the first k element's keys
const result = [];
for (let i = 0; i < k; i++) {
result.push(sortedFrequencies[i][0]);
}
return result;
}
// using object
function findKFrequentElements2(nums, k) {
// step 1: set up a count object to store count of each number
const count = {};
// step 2 : loop through the nums[]
for (let num of nums) {
// step 3 :
// set count of each number in the count object by checking
// if count already exist for that number and then adding one to it
count[num] = (count[num] || 0) + 1
}
// step 4 : sort the nums based on count in a descending order
const sortedArray = Object.keys(count).sort((a, b) => count[b] - count[a]);
// step 5 : Extract the first k elements
return sortedArray.slice(0, k);
}
// Example usage
console.log(findKFrequentElements2([1, 1, 1, 2, 2, 3], 2)); // Output: [1,2]
console.log(findKFrequentElements2([1], 1)); // Output: [1]