跳到主要内容

接雨水42

地址:https://leetcode.cn/problems/trapping-rain-water

题干

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

Image

示例 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

思路

双指针,左右两指针指向的高度谁小,就移动谁。计算当前高度与目前高度差值,加和,不断更新最大高度即可。

题解

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

int ans = 0 ;
int n = height.size();

if(n<3)return 0;

int left = 0;
int right = n-1;

int left_max = height[left];
int right_max = height[right];
while(left<right){
if(left_max<right_max){
left++;
if(height[left]>=left_max){
left_max = height[left];
}
else{
ans += left_max - height[left];
}
}else{
right--;
if(height[right]>=right_max){
right_max = height[right];
}
else{
ans += right_max - height[right];
}
}
}
return ans;
}
};

本文字数:0

预计阅读时间:0 分钟


统计信息加载中...

有问题?请向我提出issue