代码随想录算法训练营第59天|● 503.下一个更大元素II ● 42. 接雨水

● 503.下一个更大元素II

class Solution {
public:
    vector nextGreaterElements(vector& nums) {
        stack st;
        st.push(0);
        vector res(nums.size(), -1);
        for (int i = 1; i < 2 * nums.size(); i++) {
            while (!st.empty() && nums[i % nums.size()] > nums[st.top()]) {
                res[st.top()] = nums[i % nums.size()];
                st.pop();
            }
            st.push(i % nums.size());
        }
        return res;
    }
};

● 42. 接雨水

class Solution {
public:
    int trap(vector& height) {
        vector> dp(height.size(), vector(2, -1));
        dp[0][0] = -1;
        dp[height.size() - 1][1] = -1;
        for (int i = 1; i < height.size(); i ++) {
            dp[i][0] = max(height[i - 1], dp[i - 1][0]);
        }
        for (int i = height.size() - 2; i >= 0; i --) {
            dp[i][1] = max(height[i + 1], dp[i + 1][1]);
        }
        int res = 0;
        for (int i = 0; i < height.size(); i ++) {
            //printf("%d %d %d\n", dp[i][0], height[i], dp[i][1]);
            if (dp[i][0] > height[i] && height[i] < dp[i][1]) {
                res += min(dp[i][0], dp[i][1]) - height[i];
            }
        }
        return res;
    }
};

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,数据结构)