leetcode| 155. 最小棧

設計一個支持 push,pop,top 操做,並能在常數時間內檢索到最小元素的棧。

push(x) -- 將元素 x 推入棧中。
pop()  -- 刪除棧頂的元素。
top()  -- 獲取棧頂元素。
getMin() -- 檢索棧中的最小元素。java

示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top();  --> 返回 0.
minStack.getMin(); --> 返回 -2.數組

思路

以空間換時間,採用輔助棧。
輔助棧能夠分爲同步輔助棧和不一樣步輔助棧兩種。框架

同步輔助棧:
額外設置一個棧,同步保存當前數據棧的最小值,該輔助棧所push的值遞減(非嚴格遞減),pop與push操做與數據棧同步。
getMin時間複雜度O(1),空間複雜度O(n)。編碼

不一樣步輔助棧:
額外設置一個棧,保存當前數據棧的最小值,一樣也是遞減棧,pop與push操做與數據棧不一樣步:
僅當 數據棧push操做的數據 <= 輔助棧的棧頂值(最小值),輔助棧才進行push更新。
僅當 數據棧pop操做的數據 == 輔助棧的棧頂值(最小值),輔助棧才進行pop更新。
getMin時間複雜度O(1),空間複雜度O(n)。設計

代碼

  • 同步輔助棧
import java.util.*;

class MinStack {

    private Stack<Integer> data;
    
    private Stack<Integer> helper;
    
    /** initialize your data structure here. */
    public MinStack() {
        data = new Stack<Integer>();
        helper = new Stack<Integer>();
    }
    
    public void push(int x) {
        data.push(x);
        if(helper.isEmpty() || x<helper.peek()) {
            helper.push(x);
        } else {
            helper.push(helper.peek());
        }
    }
    
    public void pop() {
        if(!data.isEmpty()) {
            data.pop();
            helper.pop();
        }
    }
    
    public int top() {
        if(!data.isEmpty()) {
            return data.peek();
        }
        throw new RuntimeException("棧空,棧頂無元素");
    }
    
    public int getMin() {
        if(!data.isEmpty()) {
            return helper.peek();
        }
        throw new RuntimeException("棧空,棧無最小值");
    }
}
  • 不一樣步輔助棧
import java.util.*;

class MinStack {

    private Stack<Integer> data;
    
    private Stack<Integer> helper;
    
    /** initialize your data structure here. */
    public MinStack() {
        data = new Stack<Integer>();
        helper = new Stack<Integer>();
    }
    
    public void push(int x) {
        data.push(x);
        if(helper.isEmpty() || x<=helper.peek()) {
            helper.push(x);
        }
    }
    
    public void pop() {
        if(!data.isEmpty()) {
            if(data.peek().equals(helper.peek())) {
                helper.pop();
            }
            data.pop();
        }
    }
    
    public int top() {
        if(!data.isEmpty()) {
            return data.peek();
        }
        throw new RuntimeException("棧空,棧頂無元素");
    }
    
    public int getMin() {
        if(!data.isEmpty()) {
            return helper.get(helper.size()-1);
        }
        throw new RuntimeException("棧空,棧無最小值");
    }
}

筆記

  1. 輔助棧使用ArrayList代替Stack難以看到優點,反而下降編碼效率;
    ArrayList擴容因子爲1.5,Stack擴容因子爲2;
    Java集合框架圖:
    Java集合框架圖code

  2. data.peek().equals(helper.peek())
    包裝類型爲引用類型,不能直接等於號比較。
    Integer包裝類僅在比較的整數值在-128 - 127時能夠比較,
    Integer相關源碼:
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

當數值在-128 - 127時,靜態內部類IntegerCache使用同一cache數組共享數據。
orm

連接:https://leetcode-cn.com/problems/min-stackblog

相關文章
相關標籤/搜索