155. Min Stack
Description of Problem
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(int val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack. You must implement a solution withO(1)time complexity for each function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
-2^31 <= val <= 2^31 - 1- Methods
pop,topandgetMinoperations will always be called on non-empty stacks. - At most
3 * 10^4calls will be made topush,pop,top, andgetMin.
Solution
Tags: Stack
Explanation
Store the current minimum element on each element in the stack. And therefore, the top of the stack must contain the current minimum number.
Code
struct MinStack {
// (value, min value it knows)
stack : Vec<(i32,i32)>
}
/**
* `&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 {
stack: Vec::new()
}
}
fn push(&mut self, val: i32) {
if self.stack. len() > 0 {
self.stack.push((
val, val.min( self.get_min() )
));
} else {
self.stack.push( (val, val));
}
}
fn pop(&mut self) {
assert!(self.stack.len() > 0);
self.stack.pop();
}
fn top(&self) -> i32 {
assert!(self.stack.len() > 0);
let n = self.stack. len();
return self.stack[n - 1].0;
}
fn get_min(&self) -> i32 {
assert! (self.stack.len() > 0);
let n = self.stack. len();
return self.stack[n - 1].1;
}
}
/**
* 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();
*/
Complexity
Time Complexity
- \(T(n) = O(1)\)
Auxiliary Space
- \(S(n) = O(1)\)