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 cafa20c commit e56eacbCopy full SHA for e56eacb
top-k-frequent-elements/sunjae95.js
@@ -0,0 +1,31 @@
1
+/**
2
+ * @description
3
+ * time complexity: O(N logN)
4
+ * space complexity: O(N)
5
+ *
6
+ * brainstorming:
7
+ * 1. javascript sort method
8
+ * 2. priority queue
9
10
+ * strategy:
11
+ * javascript sort method
12
13
+ * reason:
14
+ * javascript sort method is easier to implement.
15
+ */
16
+
17
+var topKFrequent = function (nums, k) {
18
+ const answer = [];
19
+ const array = [];
20
+ const hashTable = new Map();
21
22
+ nums.forEach((num) => hashTable.set(num, (hashTable.get(num) ?? 0) + 1));
23
24
+ hashTable.forEach((count, number) => array.push({ number, count }));
25
26
+ array.sort((a, b) => b.count - a.count);
27
28
+ for (let i = 0; i < k; i++) answer.push(array[i].number);
29
30
+ return answer;
31
+};
0 commit comments