zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    2016.6.26考试
    爆搜。。。。。。。
    9.18目标
    9.17水题总结
    9.16测试
    9.10考试
    jzoj P1163 生日派对灯
    9.04考试总结
    8/8刷题记录
    a[i++]
  • 原文地址:https://www.cnblogs.com/yawenw/p/12943565.html
Copyright © 2011-2022 走看看