【Leetcode】之Trapping Rain Water

一.问题描述

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

二.我的解题思路

拿到这个题目,我开始的思路是寻找一个个凹槽,然后把它们给加起来。但是在实现的时候,在如何正确的划分一个凹槽上折腾了很久也没搞出来。我试图用if语句来分析所有可能的凹槽形状,但是难以解决本问题。随后借鉴了别人的思路,应该首先找到最大的bar。然后从两端向最大的bar逼近,这样可以确定凹槽的形状,接下来就好办了。

这套题也给我一些启发。思考问题需要一些大胆的尝试,我利用bar的下降来标识一个凹槽的开始,但是难以标识一个凹槽的结束。想法大胆一点的话,直接取最大值,那么就可以确定凹槽的形状了。
测试通过的程序如下:

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




};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值