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

503.下一个更大元素II

class Solution {
public:
    vector nextGreaterElements(vector& nums) {

        vector result(nums.size(), -1);
        stack st;
        st.push(0);

        if (nums.size() == 0) return result;

        for(int i = 1; i < 2 * nums.size(); i++){
            if(nums[i % nums.size()] <= nums[st.top()]) {
                st.push(i % nums.size());
            }else{
                while(!st.empty() && nums[i % nums.size()] > nums[st.top()]){
                    result[st.top()] = nums[i % nums.size()];
                    st.pop();
                }
                st.push(i % nums.size());
            }
        }
    return result;
    }
};

42. 接雨水

class Solution {
public:
    int trap(vector& height) {
        stack st;
        st.push(0);
        int sum = 0;
        for (int i = 1; i < height.size(); i++) {
            while (!st.empty() && height[i] > height[st.top()]) {
                int mid = st.top();
                st.pop();
                if (!st.empty()) {
                    int h = min(height[st.top()], height[i]) - height[mid];
                    int w = i - st.top() - 1;
                    sum += h * w;
                }
            }
            st.push(i);
        }
        return sum;
    }
};

84.柱状图中最大的矩形

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int result = 0;
        stack st;
        heights.insert(heights.begin(), 0); 
        heights.push_back(0); 
        st.push(0);

        for (int i = 1; i < heights.size(); i++) {
            if (heights[i] > heights[st.top()]) { 
                st.push(i);
            } else if (heights[i] == heights[st.top()]) { 
                st.pop(); 
                st.push(i);
            } else { 
                while (!st.empty() && heights[i] < heights[st.top()]) {
                    int mid = st.top();
                    st.pop();
                    if (!st.empty()) {
                        int left = st.top();
                        int right = i;
                        int w = right - left - 1;
                        int h = heights[mid];
                        result = max(result, w * h);
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};

你可能感兴趣的:(代码随想录,算法,leetcode,c++)