Skip to content

Commit 2383343

Browse files
committed
Create: 0895-maximum-frequency-stack.rs / .ts / .js
1 parent ee7a3bc commit 2383343

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class FreqStack {
2+
constructor() {
3+
this.cnt = {};
4+
this.maxCnt = 0;
5+
this.stacks = {};
6+
}
7+
8+
push(val) {
9+
let valCnt = 1 + (this.cnt[val] || 0);
10+
this.cnt[val] = valCnt;
11+
12+
if (valCnt > this.maxCnt) {
13+
this.maxCnt = valCnt;
14+
this.stacks[valCnt] = [];
15+
}
16+
this.stacks[valCnt].push(val);
17+
}
18+
19+
pop() {
20+
let res = this.stacks[this.maxCnt].pop();
21+
this.cnt[res] -= 1;
22+
23+
if (this.stacks[this.maxCnt].length == 0) {
24+
this.maxCnt -= 1;
25+
}
26+
27+
return res;
28+
}
29+
}

rust/0895-maximum-frequency-stack.rs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use std::collections::HashMap;
2+
struct FreqStack {
3+
count: HashMap<i32, i32>,
4+
max_count: i32,
5+
stacks: HashMap<i32, Vec<i32>>,
6+
}
7+
8+
impl FreqStack {
9+
fn new() -> Self {
10+
Self {
11+
count: HashMap::new(),
12+
max_count: 0,
13+
stacks: HashMap::new(),
14+
}
15+
}
16+
17+
fn push(&mut self, val: i32) {
18+
let val_count = 1 + *self.count.get(&val).or(Some(&0)).unwrap();
19+
self.count.insert(val, val_count);
20+
if val_count > self.max_count {
21+
self.max_count = val_count;
22+
self.stacks.insert(val_count, vec![]);
23+
}
24+
self.stacks.get_mut(&val_count).unwrap().push(val);
25+
}
26+
27+
fn pop(&mut self) -> i32 {
28+
let res = self.stacks.get_mut(&self.max_count).unwrap().pop().unwrap();
29+
*self.count.get_mut(&res).unwrap() -= 1;
30+
if self.stacks.get(&self.max_count).unwrap().is_empty() {
31+
self.max_count -= 1;
32+
}
33+
res
34+
}
35+
}
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class FreqStack {
2+
cnt: Map<number, number>;
3+
maxCnt: number;
4+
stacks: Map<number, number[]>;
5+
constructor() {
6+
this.cnt = new Map();
7+
this.maxCnt = 0;
8+
this.stacks = new Map();
9+
}
10+
11+
push(val: number): void {
12+
let valCnt: number = 1 + (this.cnt.get(val) || 0);
13+
this.cnt.set(val, valCnt);
14+
15+
if (valCnt > this.maxCnt) {
16+
this.maxCnt = valCnt;
17+
this.stacks.set(valCnt, []);
18+
}
19+
this.stacks.get(valCnt)?.push(val);
20+
}
21+
22+
pop(): number {
23+
let res: number = this.stacks.get(this.maxCnt)?.pop()!;
24+
this.cnt.set(res, this.cnt.get(res)! - 1);
25+
26+
if (this.stacks.get(this.maxCnt)?.length == 0) {
27+
this.maxCnt -= 1;
28+
}
29+
30+
return res;
31+
}
32+
}

0 commit comments

Comments
 (0)