leetcode weekly contest 61(739. Daily Temperatures)

来源:互联网 发布:条码追溯软件 编辑:程序博客网 时间:2024/05/22 00:29

Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].


题目

说给我们一堆天气温度
找到之后的第几天第一次比这天温度高
没找到填0


分析

先思考暴力 n平方的复杂度 , 很好写 , 就枚举即可

接着说n*logn 那么可以用线段树 倒着维护 , 不过代码较为复杂

最后说线性的复杂度 我们用单调队列维护( 一个单调递减的队列)

首先我们知道 如果有一天比前一天低那么他对于前面的温度而言是没有什么用的 , 即 tem[i-1] > tem[i] 》》如果小于i-1的天数]小于tem[i-1]那么tem[i-1]在tem[i]前生效 , 大于tem[i-1]那么tem[i]同样没有用


代码

class Solution {public:    vector<int> dailyTemperatures(vector<int>& temperatures) {        vector< int >  ans ;        if( temperatures.size() == 0 )            return ans ;        deque< int > dlist;        deque< int > index ;        ans.resize( temperatures.size() , 0 ) ;        for( int i=0 ; i<temperatures.size() ; i++){            if( dlist.size() == 0 ){                dlist.push_back( temperatures[i] ) ;                index.push_back( i );            }            else{                if( temperatures[i] <= dlist.back() ){                    dlist.push_back( temperatures[i] ) ;                    index.push_back( i ) ;                }                else{                    while( dlist.size() && dlist.back() < temperatures[i]) {                        int target = index.back() ;                        ans[target] = i - index.back() ;                        index.pop_back() ;                        dlist.pop_back() ;                    }                    dlist.push_back(temperatures[i]);                    index.push_back( i ) ;                }            }        }        return ans  ;    }};

时间复杂度 O(n) 因为每个元素出队列一次进队列一次

空间复杂度 O(n)

原创粉丝点击