Trapping Rain Water

每日算法——leetcode系列


问题 Trapping Rain Water

Difficulty: Hard

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.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

class Solution {
public:
    int trap(vector<int>& height) {

    }
};

翻译

困住的雨水

难度系数:困难

给定n个代表地图中的高度的非负数的整数,每条的宽度为1,求下雨后能困住多少雨水。
例如:
给定[0,1,0,2,1,0,1,3,2,1,2,1], 返回 6.

思路

  • 先找到最高的条柱
  • 再两边往中间扫
    1. 扫左边时,如果当前柱左边的最大值是当前柱,就记录
    2. 不是当前柱,刚把水累加

代码

class Solution {
public:
    int trap(vector<int>& height) {
        int maxBarIndex = 0;
        int index = 0;
        for (auto item : height){
            if (item > height.at(maxBarIndex)){
                maxBarIndex = index;
            }
            index++;
        }
        int water = 0;
        for (int i = 0, leftMax = 0; i < maxBarIndex; ++i){
            if (height[i] > leftMax){
                leftMax = height[i];
            } else {
                water += leftMax - height[i];
            }
        }
        int n = static_cast<int>(height.size());
        for (int i = n - 1, rightMax = 0; i > maxBarIndex; --i){
            if (height[i] > rightMax) {
                rightMax = height[i];
            } else {
                water += rightMax - height[i];
            }
        }
        return water;
    }
};

此题还有一种有栈的方式,以后再码。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值