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
  • 相关阅读:
    linux 获取外网ip地址
    出现大量rcuob进程
    禁用 ipv6
    centos yum 坏掉 db 损坏
    关于 solusvm
    VMWare 下 Ubuntu 18.04 的文件共享
    安装最新版本 nginx
    大量的Close_wait 发现的 too many open file 错
    Linux安装Desktop 和 vncserver
    MySQL in和limit不能连用的问题
  • 原文地址:https://www.cnblogs.com/yawenw/p/12943565.html
Copyright © 2011-2022 走看看