队列&栈//每日温度

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Entry> stack = new Stack<>();
        int[] res = new int[temperatures.length];
        for(int i = 0; i < temperatures.length; i++){
            if(stack.isEmpty()){
                stack.push(new Entry(temperatures[i],i));
                continue;
            }
            if(temperatures[i] <= stack.peek().val)
                stack.push(new Entry(temperatures[i],i));
            else
            {
                int j = 1;
                while(!stack.isEmpty()&&temperatures[i] > stack.peek().val){
                    Entry tmp = stack.pop();
                    res[tmp.index] = i - tmp.index;
                }
                stack.push(new Entry(temperatures[i],i));
            }
        }
        return res;
    }
    private class Entry{
        public int val;
        public int index;
        public Entry(int val,int index){
            this.val = val;
            this.index = index;
        }
    }
}
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> result;
        stack<int> record;
        for(int i = temperatures.size()-1; i>=0; i--){
            while(record.size()>0&&temperatures[record.top()]<=temperatures[i])
            {
                record.pop();
            }
            int wait_day = record.size()==0?0:record.top()-i;
            result.insert(result.begin(),wait_day);
            record.push(i);
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/strawqqhat/article/details/83961185