标签:new trie 另一个 ted 使用 example param instant removes
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
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.
最小栈,要求getMin()为检索当前stack中的最小值。
每次添加元素时用minValue来维护一个最小值
在弹出元素时,如果弹出的是最小元素,则需要在弹出后的stack中找出最小值,因为stack不能遍历,所以使用另一个tmpStack来存储原stack中弹出的每一个值找出最小元素。在将tmpStack中的值再传给原stack中。权当是一个遍历。
class MinStack { public: /** initialize your data structure here. */ MinStack() { minValue = INT_MAX; } void push(int x) { s.push(x); minValue = min(minValue, x); } void pop() { int tmp = s.top(); s.pop(); if (tmp >= minValue) { int minVal = INT_MAX; while (!s.empty()) { tmpS.push(s.top()); minVal = min(minVal, s.top()); s.pop(); } minValue = minVal; } while (!tmpS.empty()) { s.push(tmpS.top()); tmpS.pop(); } } int top() { return s.top(); } int getMin() { return minValue; } private: stack<int> s; stack<int> tmpS; int minValue; }; // 29 ms /** * 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(); */
标签:new trie 另一个 ted 使用 example param instant removes
原文地址:http://www.cnblogs.com/immjc/p/7994639.html