pub struct MinStack { /* private fields */ }
Expand description
§Solutions
§Approach 1:
-
Time complexity: O(1)
-
Space complexity: O(n)
-
Runtime: 0 ms
-
Memory: 5.2 MB
struct MinStack {
stack: Vec<i32>,
min: i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MinStack {
/** initialize your data structure here. */
fn new() -> Self {
MinStack {
stack: vec![],
min: i32::max_value(),
}
}
fn push(&mut self, x: i32) {
if self.min >= x {
self.stack.push(self.min);
self.min = x;
}
self.stack.push(x);
}
fn pop(&mut self) {
if let Some(i) = self.stack.pop() {
if i == self.min { self.min = self.stack.pop().unwrap(); }
}
}
fn top(&self) -> i32 {
*self.stack.last().unwrap()
}
fn get_min(&self) -> i32 {
self.min
}
}
/**
* Your MinStack object will be instantiated and called as such:
* let obj = MinStack::new();
* obj.push(x);
* obj.pop();
* let ret_3: i32 = obj.top();
* let ret_4: i32 = obj.get_min();
*/
Auto Trait Implementations§
impl Freeze for MinStack
impl RefUnwindSafe for MinStack
impl Send for MinStack
impl Sync for MinStack
impl Unpin for MinStack
impl UnwindSafe for MinStack
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more