LeetCode、42. 接雨水

503. 下一个更大元素 II

方法:单调栈

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

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

$时间复杂度O(n),空间复杂度O(n);

42. 接雨水

方法:双指针(超时版)

class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0, n = height.size();
        for (int i = 0; i < height.size(); ++i) {
            int rmax = height[i], lmax = height[i];
            for (int j = i + 1; j < n; ++j) if (rmax < height[j]) rmax = height[j];
            for (int j = i - 1; j >= 0; --j) if (lmax < height[j]) lmax = height[j];
            res += min(rmax, lmax) - height[i];
        }
        return res;
    }
};

$时间复杂度O(),空间复杂度O(1);

优化:

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if (n <= 2) return 0;
        vector<int> rmax(n, 0);
        vector<int> lmax(n, 0);
        lmax[0] = height[0];
        for (int i = 1; i < n; ++i) {
            lmax[i] = max(lmax[i-1], height[i]);
        }

        rmax[n-1] = height[n-1];
        for (int i = n - 2; i >= 0; --i) {
            rmax[i] = max(rmax[i+1], height[i]);
        }

        int res = 0;
        for (int i = 0; i < n; ++i) {
            res += min(rmax[i], lmax[i]) - height[i] > 0 ? min(rmax[i], lmax[i]) - height[i] : 0;
        }
        return res;
    }
};

$时间复杂度O(n),空间复杂度O(n);

方法:单调栈

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

$时间复杂度O(n),空间复杂度O(n);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值