【LeetCode】15.Trapping Rain Water

题目描述(Hard)

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. 

题目链接

https://leetcode.com/problems/trapping-rain-water/description/

Example 1:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

算法分析

方法一:存储每个位置右边最大值和左边最大值,较小者与当前height的差即为容积,时间复杂度为O(n),空间复杂度为O(n)

方法二:先找出最高的柱子,然后从左到右,从右往左依次计算容积,时间复杂度为O(n),空间复杂度为O(1)

提交代码(方法一):

class Solution {
public:
	// 方法一:存储每个位置右边最大值和左边最大值,较小者与当前height的差即为容积
	int trap(vector<int>& height) {
		int n = height.size();
		int water = 0;
		vector<int> max_left(n, 0);
		vector<int> max_right(n, 0);

		for (int i = 1; i < n; ++i)
		{
			max_left[i] = max(max_left[i - 1], height[i - 1]);
			max_right[n - 1 - i] = max(max_right[n - i], height[n - i]);
		}

		for (int i = 0; i < n; ++i)
		{
			int bound = min(max_left[i], max_right[i]);
			if (bound > height[i])
				water += bound - height[i];
		}

		return water;
	}
};

提交代码(方法二):

class Solution {
public:
	// 方法二:先找出最高的柱子,然后从左到右,从右往左依次计算容积
	int trap(vector<int>& height) {
		int max_height = 0, index = 0, water = 0;
		
		for (int i = 0; i < height.size(); ++i)
			if (height[i] > max_height)
			{
				max_height = height[i];
				index = i;
			}

		// 处理左边容积
		for (int i = 0, max_height = 0; i < index; ++i)
		{
			if (height[i] > max_height) max_height = height[i];
			else water += max_height - height[i];
		}


		// 处理右边容积
		for (int i = height.size() - 1, max_height = 0; i > index; --i)
		{
			if (height[i] > max_height) max_height = height[i];
			else water += max_height - height[i];
		}

		
		return water;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& height, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.trap(height);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{

	vector<int> height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
	Test("Test1", height, 6);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82051071