From 53cf95499d186cdc58e24b37c45a6f2fb86e0ccb Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 18 May 2024 10:05:58 +0800 Subject: [PATCH] 20240518 Finished --- src/problem/mod.rs | 3 +- src/problem/p155_min_stack.rs | 69 +++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/problem/p155_min_stack.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index fc9ed9a..6e3bfed 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -134,4 +134,5 @@ mod p228_summary_ranges; mod p56_merge_intervals; mod p57_insert_interval; mod p452_minimum_number_of_arrows_to_burst_balloons; -mod p71_simplify_path; \ No newline at end of file +mod p71_simplify_path; +mod p155_min_stack; \ No newline at end of file diff --git a/src/problem/p155_min_stack.rs b/src/problem/p155_min_stack.rs new file mode 100644 index 0000000..85cc924 --- /dev/null +++ b/src/problem/p155_min_stack.rs @@ -0,0 +1,69 @@ +/** + * [155] Min Stack + */ +pub struct Solution {} + + +// submission codes start here +use std::{cmp::Reverse, collections::BinaryHeap}; + +struct MinStack { + heap : BinaryHeap>, + stack: Vec +} + + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MinStack { + + fn new() -> Self { + MinStack { + heap: BinaryHeap::new(), + stack: vec![] + } + } + + fn push(&mut self, val: i32) { + self.heap.push(Reverse(val)); + self.stack.push(val); + } + + fn pop(&mut self) { + let n = self.stack.pop().unwrap_or(0); + + if !self.stack.contains(&n) { + self.heap.retain(|i| i.0 != n); + } + } + + fn top(&self) -> i32 { + *self.stack.last().unwrap_or(&0) + } + + fn get_min(&self) -> i32 { + self.heap.peek().unwrap_or(&Reverse(0)).0 + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * let obj = MinStack::new(); + * obj.push(val); + * obj.pop(); + * let ret_3: i32 = obj.top(); + * let ret_4: i32 = obj.get_min(); + */ + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_155() { + } +}