【LeetCode】接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例 1:
在这里插入图片描述

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

示例 2:
输入:height = [4,2,0,3,2,5]
输出:9

核心思路:

  • 左指针left)指向左端,右指针right)指向右端。
  • 我们维护两个变量:left_maxright_max,分别记录当前左端和右端的最大高度。
  • 由于右端最大高度不会变小,所以当 left_max 小于等于 right_max 时,可以确定左侧的柱子能够接住的雨水量就是 left_max - height[left],然后将左指针向右移动。
  • 反之,当 right_max 小于 left_max 时,雨水量则由 right_max 决定,并移动右指针向左。
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
class Solution 
{
public:
    int trap(vector<int>& height)
    {
        if (height.size() == 0)
            return -1;
        int left = 0;
        int right = height.size() - 1;
        int left_max = 0;
        int right_max = 0;
        int total_water = 0;
        while (left < right)
        {
            if (height[left] <= height[right])
            {
                left_max = max(left_max, height[right]);
                total_water += left_max - height[left];
                left++;
            }
            else
            {
                right_max = max(right_max, height[left]);
                total_water += right_max - height[right];
                right--;
            }
        }
        return total_water;
    }
};
int main() 
{
   
    Solution solution;
    vector<int> height1 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
    vector<int> height2 = { 4, 2, 0, 3, 2, 5 };

    cout << "Test case 1: " << solution.trap(height1) << endl;
    cout << "Test case 2: " << solution.trap(height2) << endl;

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值