LeetCode刷题-191028-Trapping Rain Water-收集雨水

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.
图片来自网站
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

有一个数组来表示每个位置的高度,计算容器能收集的雨水容量。
解题过程中我的思路是尽量通过一次遍历将结果计算出来。
个人代码如下:

public static int Trap(int[] height)
{
    int result = 0;
    int max_y = 0;
    for (int i = 0; i < height.Length; i++) 
    {
        int cur = height[i];
        if (cur > 0) 
        {
            if (max_y > 0)
            {
                int full_level = (cur < max_y) ? cur : max_y;

                for (int j = i - 1; j > 0; j--)
                {
                    if (full_level > height[j])
                    {
                        result += full_level - height[j];
                        height[j] = full_level;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (cur > max_y)
            {
                
                max_y = cur;
            }
        }
        
    }
    return result;
}

过程示意图如下:
在这里插入图片描述
我在网站的解题思路介绍里面看到了一个更加简洁的方法,示意图如下
链接地址:https://leetcode.com/articles/trapping-rain-water/
用c#重写一下,没有提交验证,仅供参考:

 public static int Trap_s(int[] height) 
 {
     int ans = 0;
     int left = 0, right = height.Length - 1;
     int left_max = height[left], right_max = height[right];
     while (left < right) 
     {
         if (height[left] < height[right])
         {
             if (left_max <= height[left])
             {
                 left_max = height[left];
             }
             else 
             {
                 ans += left_max - height[left];
             }
             left++;
         }
         else 
         {
             if (right_max <= height[right])
             {
                 right_max = height[right];
             }
             else 
             {
                 ans += right_max - height[right];
             }
             right--;
         }
     }
     return ans;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值