• 739 每日温度 && 单调栈算法的思路


    简介

    如果用暴力岂不是太不优雅了. 有些问题可以使用单调栈来进行计算.

    简单思想

    构建一个栈, 栈是一个有顺序的, 里面有一个while循环,然后 如果满足一定的条件, 将会一直弹出.

    code

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& T) {
            stack<int> s;
            vector<int> res(T.size(), 0);
            int len = T.size();
            for(int i=0; i<len; i++){
                while(!s.empty() && T[s.top()] < T[i]){
                    res[s.top()] = i - s.top();
                    s.pop();
                }
                s.push(i);
            }
            return res;
        }
    };
    
    class Solution {
        public int[] dailyTemperatures(int[] T) {
            Deque<Integer> stack = new ArrayDeque<>();
    
            int [] res = new int[T.length];
            for(int i = 0; i<T.length; i++){
                while(!stack.isEmpty() && T[stack.peek()] < T[i]){
                    int idx = stack.pop();
                    res[idx] = i - idx;
                }
                stack.push(i);
            }
            return res;
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    离线安装MariaDB 10.4.13
    YUM 的使用
    Crontab 定时任务
    静默安装卸载 ORACLE
    java 改变图片的DPI
    Java TIF、JPG、PNG等图片转换
    key可重复的Map
    集合对象去重
    Java创建TXT文件并写入 内容
    Java已知图片路径下载图片到本地
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14844150.html
Copyright © 2020-2023  润新知