1. 程式人生 > >佇列&棧//每日溫度

佇列&棧//每日溫度

根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度才會升高的天數。如果之後都不會升高,請輸入 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;
    }
};