Leetcode Study Day 27

Min Stack

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 element val onto 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 with O(1) time complexity for each function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

-231 <= val <= 231 - 1
Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 104 calls will be made to push, pop, top, and getMin.

My solution

Every function is straight forward and eay to write, except for the getMin() function. I used a vector to store the minimum value of the stack. The method I use is create two vectors (we can use stack of course), one is the main Stack, which I called miniStack, and the other stack is to store the min values, which is miniOrder in my code.

Once we push a value into the stack, we check whether the value is smaller than the top of the miniOrder. If it is, we push the value into the miniOrder and miniStack. If it is not, we only push the value into the miniStack.

Once we try to use pop function, before we pop the value in the mainStack, we first check whether this value is equal to the top of the miniOrder. If it is, we pop the value in the miniOrder and miniStack. If it is not, we only pop the value in the miniStack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class MinStack {
public:
MinStack() {
miniStack.clear();
miniOrder.clear();
}

void push(int val) {
miniStack.push_back(val);
if (miniOrder.empty())
miniOrder.push_back(val);
else if(miniOrder.back()>= val)
miniOrder.push_back(val);
}

void pop() {
if(!miniOrder.empty()){
if (miniOrder.back() == miniStack.back())
miniOrder.pop_back();
}
if (!miniStack.empty())
miniStack.pop_back();
}

int top() {
return miniStack.back();
}

int getMin() {
return miniOrder.back();
}
private:
vector <int> miniStack;
vector <int> miniOrder;
};

/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信