advancing6

题目描述[原题链接][https://leetcode-cn.com/problems/min-stack/]

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) – 将元素 x 推入栈中。
  • pop() – 删除栈顶的元素。
  • top() – 获取栈顶元素。
  • getMin() – 检索栈中的最小元素。

示例:

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

算法描述

初始化两个栈,一个用于存放每次进来的数据,另一个用来存放当前数据的最小值,当有元素压入时,需要判断存放最小值的栈的栈顶元素是否比压入的元素小,如果小,将这个元素压入栈中,如果最小值的栈是空的直接压入即可,弹栈时也需要判断是否弹出的元素是否为当前最小栈的栈顶元素,如果是需要做弹出操作;

C++代码

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
class MinStack {
public:
/** initialize your data structure here. */
stack<int> sta;
stack<int> min;
MinStack() {
}

void push(int x) {
sta.push(x);
if(min.empty()||x<=min.top())min.push(x);
}

void pop() {
if(sta.top()==min.top()){
min.pop();
}
sta.pop();
}

int top() {
return sta.top();
}

int getMin() {
return min.top();
}
};

/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/

Java代码

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
class MinStack {

/** initialize your data structure here. */
Stack<Integer> sta;
Stack<Integer> min;
public MinStack() {
sta = new Stack<Integer>();
min = new Stack<Integer>();
}

public void push(int x) {
sta.push(x);
if(min.empty()||min.peek()>=x)min.push(x);
}

public void pop() {
int t = sta.pop();
if(t == min.peek())min.pop();
}

public int top() {
return sta.peek();
}

public int getMin() {
return min.peek();
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/