leetCode Min Stack解題分享,leetcodestack

來源:互聯網
上載者:User

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());    }    }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.