LeetCode 739. 每日温度 Daily Temperatures (Medium)

来源:力扣(LeetCode)

解法一:辅助栈。

在遍历数组时用栈把数组中的数存起来,如果当前遍历的数比栈顶元素来的大,说明栈顶元素的下一个比它大的数就是当前元素。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {

        vector<int> dist(T.size());
        stack<int> indexs;  //保存位置
        for (int curIndex = 0; curIndex < T.size(); ++curIndex)
        {   
            while (!indexs.empty() && T[curIndex] > T[indexs.top()])
            {
                int preIndex = indexs.top(); indexs.pop();
                dist[preIndex] = curIndex - preIndex;
            }
            indexs.push(curIndex);
        }
        return dist;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12897980.html