We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b1728a9 commit 10b4ae1Copy full SHA for 10b4ae1
top-k-frequent-elements/prgmr99.js
@@ -0,0 +1,33 @@
1
+/**
2
+ * @param {number[]} nums
3
+ * @param {number} k
4
+ * @return {number[]}
5
+ */
6
+var topKFrequent = function (nums, k) {
7
+ const result = [];
8
+ const numMap = new Map();
9
+
10
+ for (let i = 0; i < nums.length; i++) {
11
+ const currentValue = numMap.get(nums[i]);
12
13
+ if (currentValue) {
14
+ numMap.set(nums[i], currentValue + 1);
15
+ } else {
16
+ numMap.set(nums[i], 1);
17
+ }
18
19
20
+ const mapToArr = [...numMap.entries()];
21
22
+ mapToArr.sort((a, b) => {
23
+ if (a[1] < b[1]) return 1;
24
+ if (a[1] > b[1]) return -1;
25
+ return 0;
26
+ });
27
28
+ for (let i = 0; i < k; i++) {
29
+ result.push(mapToArr[i][0]);
30
31
32
+ return result;
33
+};
0 commit comments