接雨水(栈/双指针)

题目:
参考:https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
栈解法

class Solution {
public:
    int trap(vector<int>& height) {
        /*
        *给定n个非负整数表示每个宽度为1的柱子的高度图,
        *计算按此排列的柱子,下雨之后能接多少雨水。
        *栈:对于当前柱子,如果高度比栈顶的小,入栈;
        *如果高度大于栈顶,说明栈顶柱子高度介于前一个和
        *当前柱子
        */
        int n = height.size();
        if(n <= 2) return 0;
        int sum = 0;
        stack<int> st;
        st.push(0);
        for(int i = 1,x;i < n;i++) {
            while(!st.empty() && height[st.top()] <= height[i]) {
                x = st.top();st.pop();
                if(!st.empty()) {
                    sum += (min(height[st.top()],height[i])-height[x])*(i-st.top()-1);
                    printf("id:%d s:%d\n ",i,sum);
                }
            }
            st.push(i);
            
        }
        return sum;
    }
};

双指针

class Solution {
public:
    int trap(vector<int>& height) {
        /*
        *给定n个非负整数表示每个宽度为1的柱子的高度图,
        *计算按此排列的柱子,下雨之后能接多少雨水。
        *双指针:能盛水的柱子必然其左侧和右侧都高于它,
        *由木桶理论,每次舍去左右侧较短的,移动指针,
        *更新答案,直到遇到比当前短柱子更大的柱子
        */
        int n = height.size();
        if(n <= 2) return 0;
        int sum = 0;
        int l = 0,r = n-1,pos;
        while(l < r) {
            if(height[l] < height[r]) {
                pos = l+1;
                while(pos <=r && height[pos] <= height[l]) { 
                    sum += height[l]-height[pos];
                    pos++;
                }
                l = pos;
            }else {
                pos = r-1;
                 while(pos >= l && height[pos] <= height[r]) { 
                    sum += height[r]-height[pos];
                    pos--;
                }
                r = pos;
            }
        }
        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值