LeetCode – Daily Temperatures

题目:

 Daily Temperatures
 

Given a list of daily temperatures T, return a list such 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 of temperatures T = [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].

解题:

       使用单调栈如果当前数据比栈顶小则入栈, 如果比栈顶元素大,则出栈并循环处理将所有比当前元素小的栈内元素出栈。

       入栈操作数据为数据索引,出栈时, 计算当前索引与出栈元素(对应数据索引)差值即为元素距离, 设置到对应的vector上并返回。  

实现:

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        int  n= T.size();
        vector<int> res(n, 0);
        stack<int> ss;
        for (int i=0; i<n; i++){
            while (!ss.empty() && T[i] > T[ss.top()]){
                auto t = ss.top();
                ss.pop();
                res[t] = i - t;
            }
            ss.push(i);
        }
        return res;
    }
};

Be First to Comment

发表回复