标签:constant element empty iat led min() get value tac
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.
public class MinStack { Stack<Long> stack; int min; /** initialize your data structure here. */ public MinStack() { stack = new Stack<Long>(); min = 0; } public void push(int x) { if (stack.isEmpty()) { min = x; stack.push(0L); return; } stack.push((long)x - min); if (x < min) { min = x; } } public void pop() { long cur = stack.pop(); if (cur < 0) { min = (int)(min - cur); } } public int top() { if (stack.peek() < 0L) { return min; } else { return (int)(min + stack.peek()); } } public int getMin() { return min; } } /** * 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(); */
另一种办法
分析:保存到目前为止的最小值。当出栈导致更新最小值时,如果记录了之前的最小值信息,就能更新到pop出当前元素后的最小值。
public class MinStack { Stack<Integer> stack; int min; /** initialize your data structure here. */ public MinStack() { stack = new Stack<Integer>(); min = Integer.MAX_VALUE; } public void push(int x) { if (x <= min) { //这里要用<=。如果x == min,x也会被判断为新的最小值,在pop时连pop两次,因此此时也要push两次 stack.push(min); min = x; } stack.push(x); } public void pop() { int cur = stack.pop(); if (cur == min) { min = stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return min; } } /** * 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(); */
标签:constant element empty iat led min() get value tac
原文地址:http://www.cnblogs.com/yuchenkit/p/7169507.html