LeetCode算法 —— 接雨水

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

在这里插入图片描述

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

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


双指针计算单柱子:

#include <iostream> 
#include <algorithm>
#include <vector>   
#include <stack>
using namespace std;

class Solution {
public:
	int trap(vector<int>& height)
	{
		int left = 0, right = height.size() - 1;
		int retNum = 0;		// 返回的数

		int leftMax = 0, rightMax = 0;				// 左边和右边当前最大的数

		while (left < right) {
			// 处理较小的那一边
			if (height[left] < height[right]) {
				if (height[left] >= leftMax) {
					leftMax = height[left];				// 先获取当前最高的那个柱子
				}
				else {
					retNum += (leftMax - height[left]);	// 加上当前柱子上面的水
				}

				++left;
			}
			else {
				if (height[right] >= rightMax) {
					rightMax = height[right];
				}
				else {
					retNum += (rightMax - height[right]);
				}

				--right;
			}
		}

		return retNum;
	} 
};


int main() {
	vector<int> arr{ 0,1,0,2,1,0,1,3,2,1,2,1 };


	cout << (new Solution())->trap(arr);


	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42100963/article/details/107772102