Skip to content

Commit 392389f

Browse files
committed
https://leetcode.cn/problems/maximum-frequency-stack
1 parent a3f05dd commit 392389f

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Step 2. Add the dependency
4545

4646
<summary>展开查看</summary>
4747

48+
https://leetcode.cn/problems/maximum-frequency-stack
49+
4850
https://leetcode.cn/problems/calculate-amount-paid-in-taxes
4951

5052
https://leetcode.cn/problems/third-maximum-number/

maximum-frequency-stack/index.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class FreqStack {
2+
#freq: Map<number, number>;
3+
#group: Map<number, number[]>;
4+
#maxFreq: number;
5+
constructor() {
6+
this.#freq = new Map();
7+
this.#group = new Map();
8+
this.#maxFreq = 0;
9+
}
10+
11+
push(val: number): void {
12+
this.#freq.set(val, (this.#freq.get(val) || 0) + 1);
13+
const cnt = this.#freq.get(val) ?? 0;
14+
15+
if (!this.#group.has(cnt)) {
16+
this.#group.set(cnt, []);
17+
}
18+
this.#group.get(cnt)?.push(val);
19+
this.#maxFreq = Math.max(this.#maxFreq, cnt);
20+
}
21+
22+
pop(): number {
23+
const array = this.#group.get(this.#maxFreq) ?? [];
24+
25+
const val = array[array.length - 1];
26+
this.#freq.set(val, (this.#freq.get(val) ?? 0) - 1);
27+
array.pop();
28+
29+
if (array.length === 0) {
30+
this.#maxFreq--;
31+
}
32+
return val;
33+
}
34+
}
35+
export default FreqStack;

0 commit comments

Comments
 (0)