155. Min Stack

2018/04/29 leetcode 共 854 字,约 3 分钟

Title

the problem link

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.

pop() – Removes the element on top of the stack.

top() – Get the top element.

getMin() – Retrieve the minimum element in the stack.

Example:

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

这题以前见过,但忘记哪里见到的了,就是采用两个栈,一个栈保存正常的数据,另一个保存当前栈里面的最小值,只要改下这个push和pop就好了

Solution

//cpp:
class MinStack {
public:
	/** initialize your data structure here. */
	int min1;
	stack<int> a, b;
	MinStack() {
		min1 = INT_MAX;
	}

	void push(int x) {
		min1 = min(min1, x);
		a.push(x);
		b.push(min1);
	}

	void pop() {
		a.pop();
		b.pop();
		if (b.empty())
			min1 = INT_MAX;
		else
			min1 = b.top();
	}

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

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

Search

    Table of Contents