Skip to content

Commit d79ab13

Browse files
authored
Update Top K Frequent Elements - Leetcode 347.js
1 parent 49a60fe commit d79ab13

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.js

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,106 @@
1+
var topKFrequent = function(nums, k) {
2+
const countMap = new Map();
3+
for (const num of nums) {
4+
countMap.set(num, (countMap.get(num) || 0) + 1);
5+
}
6+
7+
const heap = new MinHeap();
8+
9+
for (const [num, freq] of countMap) {
10+
if (heap.size() < k) {
11+
heap.add([freq, num]);
12+
} else {
13+
heap.add([freq, num]);
14+
heap.poll();
15+
}
16+
}
17+
18+
return heap.toArray().map(pair => pair[1]);
19+
};
20+
21+
// Helper class for MinHeap
22+
class MinHeap {
23+
constructor() {
24+
this.heap = [];
25+
}
26+
27+
size() {
28+
return this.heap.length;
29+
}
30+
31+
add(pair) {
32+
this.heap.push(pair);
33+
this.bubbleUp();
34+
}
35+
36+
poll() {
37+
const min = this.heap[0];
38+
const end = this.heap.pop();
39+
if (this.size() > 0) {
40+
this.heap[0] = end;
41+
this.bubbleDown();
42+
}
43+
return min;
44+
}
45+
46+
bubbleUp() {
47+
let idx = this.size() - 1;
48+
const element = this.heap[idx];
49+
while (idx > 0) {
50+
let parentIdx = Math.floor((idx - 1) / 2);
51+
let parent = this.heap[parentIdx];
52+
if (element[0] >= parent[0]) break;
53+
this.heap[idx] = parent;
54+
idx = parentIdx;
55+
}
56+
this.heap[idx] = element;
57+
}
58+
59+
bubbleDown() {
60+
let idx = 0;
61+
const length = this.size();
62+
const element = this.heap[0];
63+
while (true) {
64+
let leftChildIdx = 2 * idx + 1;
65+
let rightChildIdx = 2 * idx + 2;
66+
let swap = null;
67+
68+
if (leftChildIdx < length) {
69+
let leftChild = this.heap[leftChildIdx];
70+
if (leftChild[0] < element[0]) {
71+
swap = leftChildIdx;
72+
}
73+
}
74+
75+
if (rightChildIdx < length) {
76+
let rightChild = this.heap[rightChildIdx];
77+
if ((swap === null && rightChild[0] < element[0]) ||
78+
(swap !== null && rightChild[0] < this.heap[swap][0])) {
79+
swap = rightChildIdx;
80+
}
81+
}
82+
83+
if (swap === null) break;
84+
this.heap[idx] = this.heap[swap];
85+
idx = swap;
86+
}
87+
this.heap[idx] = element;
88+
}
89+
90+
toArray() {
91+
return this.heap;
92+
}
93+
}
94+
95+
96+
97+
98+
99+
100+
101+
102+
103+
1104
var topKFrequent = function(nums, k) {
2105
const count = new Map();
3106
for (const num of nums) {

0 commit comments

Comments
 (0)