leetCode Min Stack解題分享,leetcodestack
原題:https://oj.leetcode.com/problems/min-stack/
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.
題目其實不難,但是是leetCode今天剛剛新增的一個題目,索性搶個頭彩把解題過程分享出來:
直接上AC代碼:
public class MinStack {private int min = Integer.MAX_VALUE;private int minIndex = -1;private ArrayList<Integer> stack = new ArrayList<Integer>();private int length = 0;private HashMap<Integer,Integer> secondMinMap = new HashMap<Integer, Integer>(); public void push(int x) { stack.add(x); if(x <= min) { //注意這裡犯過錯誤,需要加=號,原因是當棧空的時候如果push一個Integer.MaxValue的話,需要將此時的minIndex變為0而不是繼續為-1。 //否則的話,這種情況下,當push第二個數的時候,將出現secondMap.put(1,-1)的情況,進而當pop這個數的時候,會出現stack.get(-1)操作。 //換句話說,這個secondMap裡的值只有當key=0的時候,才能為-1,其他情況必須有能指向數組裡位置的值 secondMinMap.put(length, minIndex); //這裡存的 length位置對應的第二小的,只考慮比length小的索引即可 //因為用到的情境是當前這個如果被pop了,說明它上面的所有都已經被pop了 //這個時候如果當前是min,那麼接下來只需要在它下面去找第二小的就行了 minIndex = length; min = x; } length ++; } public void pop() { if(length == 0) return; if(minIndex == length-1) { if(minIndex == 0) { minIndex = -1; min = Integer.MAX_VALUE; } else { minIndex = secondMinMap.get(length-1); secondMinMap.remove(length-1); min = stack.get(minIndex); } } stack.remove(length-1); length--; } public int top() { return stack.get(length-1); } public int getMin() { return min; } public static void main(String[] args) { MinStack stack = new MinStack(); stack.push(2147483646); stack.push(2147483646); stack.push(2147483647); System.out.println(stack.top()); stack.pop(); System.out.println(stack.getMin()); stack.pop(); System.out.println(stack.getMin()); stack.pop(); stack.push(2147483647); System.out.println(stack.top()); System.out.println(stack.getMin()); stack.push(-2147483648); System.out.println(stack.top()); System.out.println(stack.getMin()); stack.pop(); System.out.println(stack.getMin()); } }