Leetcode 42. Trapping Rain Water
2016-11-04 14:31
405 查看
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
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. Thanks Marcos for contributing this image!
大致意思是求条形图形的蓄水能力。也即图中的蓝色阴影面积。
这里说下思路以备用:
首先看到这题的时候并没有什么思路来做,后来看了下标签,提示是双指针。然后思考:什么样的情况下可以蓄水?蓄水面积要如何计算?不妨考虑某个时刻两端的高度为left和right。此时,则应该从低向高位扩展,并且有扩展过程可以计算经过路径的蓄水面积。
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
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. Thanks Marcos for contributing this image!
大致意思是求条形图形的蓄水能力。也即图中的蓝色阴影面积。
这里说下思路以备用:
首先看到这题的时候并没有什么思路来做,后来看了下标签,提示是双指针。然后思考:什么样的情况下可以蓄水?蓄水面积要如何计算?不妨考虑某个时刻两端的高度为left和right。此时,则应该从低向高位扩展,并且有扩展过程可以计算经过路径的蓄水面积。
public int trap(int[] height) { if (height == null || height.length < 3) { return 0; } int res = 0; int left = 0, right = height.length - 1; while (left < right) { int min = height[left] > height[right] ? height[right] : height[left]; if (min == height[left]) { while (++left < right && height[left] <= min) { res += min - height[left]; } } else { while (left < --right && height[right] <= min) { res += min - height[right]; } } } return res; }
相关文章推荐
- Leetcode: 42. Trapping Rain Water
- leetcode.array--42. Trapping Rain Water
- 第一周:[leetcode] 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water(收集雨水Ⅰ)
- LeetCode 42. Trapping Rain Water(装雨水)
- Leetcode 42. Trapping Rain Water (Hard) (cpp)
- [LeetCode] 42. Trapping Rain Water 解题思路
- [LeetCode] 42. Trapping Rain Water 收集雨水
- [leetcode]42. Trapping Rain Water(Java)
- [array] leetcode - 42. Trapping Rain Water - Hard
- 42. Trapping Rain Water leetcode Python 2016 new season
- LeetCode 42. Trapping Rain Water 题解
- [LeetCode]42. Trapping Rain Water
- LeetCode------42. Trapping Rain Water(捕获雨水量)
- [LeetCode]42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- leetcode题解-42. Trapping Rain Water
- LeetCode题目:42. Trapping Rain Water
- 面试算法——双指针的应用leetcode 42. Trapping Rain Water
- leetcode 42. Trapping Rain Water 正反循环遍历求解