【LeetCode】42. Trapping Rain Water

42. Trapping Rain Water

Description:
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.
Difficulty:Hard
Example:

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

在这里插入图片描述

方法1:暴力求解
  • Time complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
    思路:
    对每个元素分别寻找左边最大和右边最大,注意需要考虑自身
class Solution {
public:
	int trap(vector<int>& height) {
		int res = 0;
		for (int i = 1; i < height.size(); i++) {
			int left_max = 0, right_max = 0;
			for (int j = i; j >= 0; j--)
				left_max = max(left_max, height[j]);
			for (int j = i; j < height.size(); j++)
				right_max = max(right_max, height[j]);
			res += min(left_max, right_max) - height[i];
		}
		return res;
	}
};
方法2:存储法
  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( n ) O\left ( n \right ) O(n)
    思路:
    其实和方法一目标一致,但是是通过遍历记录小来左边最大和右边最大的。
class Solution {
public:
	int trap(vector<int>& height) {
		if (height.size() == 0) return 0;
		int res = 0, len = height.size();
		vector<int> left(len), right(len);
		left[0] = height[0], right[len - 1] = height[len - 1];
		for (int i = 1; i < len; i++)
			left[i] = max(height[i], left[i - 1]);
		for (int i = len - 2; i >= 0; i--)
			right[i] = max(height[i], right[i + 1]);
		for (int i = 1; i < len - 1; i++)
			res += min(left[i], right[i]) - height[i];
		return res;
	}
};
方法2:双指针
  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
    思路:
    仔细思考方法二,可以发现max都是随着指针移动一致增加的,所以在指针移动时可以直接计算,但是要注意height[l] height[r]谁小谁移动,因为大的作为相对一侧的坚实挡板
class Solution {
public:
	int trap(vector<int>& height) {
		int res = 0,l = 0, r = height.size() - 1;
		int left_max = 0, right_max = 0;
		while (l < r) {
			if (height[l] < height[r]) {
				height[l] >= left_max ? left_max = height[l] : res += left_max - height[l];
				l++;
			}
			else {
				height[r] >= right_max ? right_max = height[r] : res += right_max - height[r];
				r--;
			}
		}
		return res;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值