LeetCode 895. Maximum Frequency Stack

Problem Statement


use std::collections::HashMap;
use std::cmp;

struct FreqStack {
mx_freq: i32,
freq: HashMap<i32, i32>,
m: HashMap<i32, Vec<i32>>
}

impl FreqStack {

fn new() -> Self {
FreqStack {
mx_freq: 0,
freq: HashMap::new(),
m: HashMap::new()
}
}

fn push(&mut self, x: i32) {
self.freq.entry(x).or_insert(0);
*self.freq.get_mut(&x).unwrap() += 1;
let val = *self.freq.get(&x).unwrap();
self.mx_freq = cmp::max(self.mx_freq, val);
self.m.entry(val).or_insert(vec![]);
self.m.get_mut(&val).unwrap().push(x);
}

fn pop(&mut self) -> i32 {
let x = self.m.get(&self.mx_freq).unwrap().last().unwrap().clone();
self.m.get_mut(&self.mx_freq).unwrap().pop();
let val = self.freq.get(&x).unwrap();
if !self.m.contains_key(val) || self.m.get(val).unwrap().is_empty() {
self.mx_freq -= 1;
}
*self.freq.get_mut(&x).unwrap() -= 1;
return x;
}
}