算法刷题Day 58 每日温度+下一个更大元素I

Day 58 单调栈

739. 每日温度

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> rst(temperatures.size());
        vector<int> decsStk; // 单调递减栈

        for (int i = 0; i < temperatures.size(); i++)
        {
            while (!decsStk.empty() && temperatures[decsStk.back()] < temperatures[i])
            {
                rst[decsStk.back()] = i - decsStk.back();
                decsStk.pop_back();
            }

            decsStk.push_back(i);
        }

        return rst;
    }
};

496. 下一个更大元素I

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> decsStk; // 存放nums2的下标
        unordered_map<int, int> table;
        
        for (int i = 0; i < nums2.size(); ++i)
        {
            while (!decsStk.empty() && nums2[decsStk.back()] < nums2[i])
            {
                table[nums2[decsStk.back()]] = nums2[i];
                decsStk.pop_back();
            }
            decsStk.push_back(i);
        }

        vector<int> rst(nums1.size(), -1);
        for (int i = 0; i < nums1.size(); i++)
        {
            if (table.find(nums1[i]) != table.end())
            {
                rst[i] = table[nums1[i]];
            }
        }

        return rst;
    }
};

你可能感兴趣的:(算法)