class MinStack { ArrayListstack = new ArrayList (); ArrayList minStack = new ArrayList (); public void push(int x) { // check min stack.add(x); if ( minStack.isEmpty() || minStack.get( minStack.size()-1 ) >= x ) { minStack.add(x); } } public void pop() { // top if ( stack.isEmpty() ) { return; } int elem = stack.remove( stack.size() -1 ); if ( !minStack.isEmpty() && elem == minStack.get(minStack.size() -1 ) ) { minStack.remove( minStack.size() -1 ); } } public int top() { // top if (! stack.isEmpty() ) { return stack.get( stack.size() - 1 ); } return 0; } public int getMin() { // top if ( !minStack.isEmpty() ) { return minStack.get( minStack.size() -1 ); } return 0; } }
Saturday, July 11, 2015
[Leetcode]07/09 [Data Structure]Min Stack
/*
Time:O(1), Space:O(n)
push O(1)
pop O(1)
top O(1)
getMin O(1)
*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment