代码随想录Day61 | 503. 下一个更大元素 II | 42. 接雨水

503. 下一个更大元素 II

class Solution {
public:
    vector nextGreaterElements(vector& nums) {
        stack st;
        int n = nums.size();
        vector res(n,-1);
        for(int i=0;i

42. 接雨水

暴力法(最后一个用例超时)

class Solution {
public:
    int trap(vector& height) {
        int n=height.size();
        int sum=0;
        for(int i=0;i= 0; l--) {
            lHeight = max(lHeight,height[l]);
            }
            int h = min(lHeight,rHeight)-height[i];
            if(h>0)
            sum+=h;
        }
        return sum;
    }
};

暴力优化法(双指针)

class Solution {
public:
    int trap(vector& height) {
        int n = height.size();
        if(n<=2) return 0;
        vector lmaxh(n,0);
        vector rmaxh(n,0);  //把两边的最高的柱子用数组存起来,以空间换时间
        lmaxh[0]=height[0];
        int sum=0;
        for(int i=1;i=0;i--){
            rmaxh[i] = max(height[i],rmaxh[i+1]);
        }
        for(int i=0;i0)
            sum+=h;
        }
        return sum;
    }
};

单调栈法

class Solution {
public:
    int trap(vector& height) {
        stack st;  //存储下标
        int n = height.size();
        int sum=0;
        for(int i=0;iheight[st.top()]){
                    int mid = st.top();
                    st.pop();
                    if(st.size()){
                        int h = min(height[st.top()],height[i])-height[mid];
                        int w = i-st.top()-1;
                        sum+=h*w;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
};

你可能感兴趣的:(算法题练习,算法,数据结构,leetcode)