May LeetCoding Challenge19 之 单调栈2.0

本题解法主要维护两个栈,一个是价格prices的单调递减栈。一个是weights栈随着prices 一起进栈出栈,计算w。

因为两个栈是一起进出,所以可以将两个栈写在一起Deque<List<>>

JAVA

class StockSpanner {
    Deque<Integer> prices;
    Deque<Integer> weights;
    public StockSpanner() {
        prices = new LinkedList<>();
        weights = new LinkedList<>();
    }
    
    public int next(int p) {
        int w = 1;
        while(!prices.isEmpty() && prices.getLast() <= p){
            prices.removeLast();
            w += weights.removeLast();
        }
        prices.addLast(p);
        weights.addLast(w);
        return w;
    }
}

 

class StockSpanner {
    Deque<List<Integer>> prices;
    public StockSpanner() {
        prices = new LinkedList<>();
    }
    
    public int next(int p) {
        int w = 1;
        while(!prices.isEmpty() && prices.getLast().get(0) <= p){
            w += prices.removeLast().get(1);
        }
        List<Integer> temp = new LinkedList<>();
        temp.add(p);
        temp.add(w);
        prices.addLast(temp);
        return w;
    }
}

 

Python3

class StockSpanner:
 
    def __init__(self):
        self.prices = []
 
    def next(self, p):
        """
        :type price: int
        :rtype: int
        """
        w = 1
        while len(self.prices) and self.prices[-1][0]<=p:
            w += self.prices.pop()[1]
        self.prices.append([p,w])
        return w

 

posted @ 2020-05-23 17:31  yawenw  阅读(139)  评论(0编辑  收藏  举报