LeedCode_接雨水

LeedCode_接雨水

题目说明

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

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

链接:https://leetcode-cn.com/problems/trapping-rain-water
参考文章:https://blog.csdn.net/kexuanxiu1163/article/details/100681468
关键思路:在某一个位置的储水量=min(左最大值,右最大值)-height

int trap(vector<int>& height) 
{
	int n = height.size();
	if (n == 0)
	{
		return 0;
	}
	vector<int> right(n,0);
	vector<int> left(n,0);
	for (int i = 1; i < n-1; i++)
	{
		left[i] = max(height[i-1], left[i - 1]);
		right[n - 1 - i] = max(height[n - i], right[n - i]);
	}
	int ans=0;
	int temp;
	for (int i = 0; i < n; i++)
	{
		temp = min(left[i], right[i]) - height[i];
		if (temp < 0)
			continue;
		ans += temp;
	}
	return ans;
}
发布了26 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/luncy_yuan/article/details/104069130