Min Stack 最小栈

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

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

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

思路:我们需要两个辅助栈s1和s2,s1为操作栈,s2为最小栈,其中除了getMin函数是返回s2的栈顶元素以外,其他返回的值都是s1的,那么是怎么保证每次都能取栈中最小的值的,只要保证每次压栈时s2中都压入s2栈顶元素和待压入元素x的最小值即可。

ope                s1              s2

push(-2)         -2               -2

push(1)         -2,1           -2,-2

push(-1)      -2,1,-1       -2,-2,-2

push(-9)     -2,1,-1,-9   -2,-2,-2,-9

参考代码:

class MinStack {
public:
	/** initialize your data structure here. */
	MinStack() {

	}

	void push(int x) {
		if (s2.empty()) {
			s2.push(x);
		}
		else {
			s2.push(min(s2.top(), x));
		}
		s1.push(x);
	}

	void pop() {
		if (!s1.empty()) {
			s1.pop();
			s2.pop();
		}
	}

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

	int getMin() {
		return s2.top();
	}
private:
	stack<int> s1, s2;
};

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/81584074