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. 題解: 設計一個棧,能夠實現出入棧,獲得棧頂元素,而且能不斷獲得出入棧操作後棧內最小的元素。
解決思路: 1、由於要不斷在出入棧操作後獲得棧內最小的元素,所以並不能直接在類裡用一個min變數來儲存最小的元素,因為這樣無法更新min的值。由此就設計了一個內部類,但這裡有一個問題,如果我們單純的設計一個普通的內部類,提交後會memory limited exceeded。單步調試會發現,每一個內部類對象都會包含一個this,然後這個this又包含了我們的棧,會浪費非常多的空間。這個時候我想起了用static修飾內部類,讓其變成靜態類,然後就OK了。 想要深入瞭解的話可以看看我轉載的這個文章:http://blog.csdn.net/u012403246/article/details/41243319 2、設計兩個棧,一個棧儲存資料,第二個棧儲存對應最小值。 3、或者不使用JAVA包裡的Stack,自己通過設計類去得到一個棧,實現以上功能.
三、代碼: 1、
class MinStack {Stack<Elem> stack = new Stack<MinStack.Elem>(); public void push(int x) { if(stack.isEmpty() || x < stack.peek().min){ stack.push(new Elem(x, x)); }else{ stack.push(new Elem(stack.peek().min, x)); } } public void pop() { stack.pop(); } public int top() { return stack.peek().val; } public int getMin() { return stack.peek().min; } public static class Elem{ int min; int val; public Elem(int min,int val) { this.min = min; this.val = val;} }}2、by: zkfairytale
class MinStack { // stack: store the stack numbers private Stack<Integer> stack = new Stack<Integer>(); // minStack: store the current min values private Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { // store current min value into minStack if (minStack.isEmpty() || x <= minStack.peek()) minStack.push(x); stack.push(x); } public void pop() { // use equals to compare the value of two object, if equal, pop both of them if (stack.peek().equals(minStack.peek())) minStack.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); }}
3、by: wyyw2882
class MinStack { Node top = null; public void push(int x) { if (top == null) { top = new Node(x); top.min = x; } else { Node temp = new Node(x); temp.next = top; top = temp; top.min = Math.min(top.next.min, x); } return; } public void pop() { top = top.next; return; } public int top() { return top == null ? 0 : top.val; } public int getMin() { return top == null ? 0 : top.min; } } class Node { int val; int min; Node next; public Node(int val) { this.val = val; } }