Leetcode 42 Trapping Rain Water
2017-05-22 15:38
429 查看
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
双指针的问题啊,重点在于,怎么判断当前能够存住水。
思考一下,存住的水取决于左右两块板的高度,首先要都大于零,并且受短板的牵制。
plank就相当于从两侧开始造一个木桶,plank的大小就是高度,只增不减,遇到比plank矮的就能储水
如果继续遇到新的plank就更新plank的值
public class Solution {
public int trap(int[] A) {
int i = 0, j = A.length - 1, result = 0, plank = 0;
while(i <= j){
plank = plank < Math.min(A[i], A[j]) ? Math.min(A[i], A[j]) : plank;
result = A[i] >= A[j] ? result + (plank - A[j--]) : result + (plank - A[i++]);
}
return result;
}
}
For example,
Given
[0,1,0,2,1,0,1,3,2,1,2,1], return
6.
双指针的问题啊,重点在于,怎么判断当前能够存住水。
思考一下,存住的水取决于左右两块板的高度,首先要都大于零,并且受短板的牵制。
plank就相当于从两侧开始造一个木桶,plank的大小就是高度,只增不减,遇到比plank矮的就能储水
如果继续遇到新的plank就更新plank的值
public class Solution {
public int trap(int[] A) {
int i = 0, j = A.length - 1, result = 0, plank = 0;
while(i <= j){
plank = plank < Math.min(A[i], A[j]) ? Math.min(A[i], A[j]) : plank;
result = A[i] >= A[j] ? result + (plank - A[j--]) : result + (plank - A[i++]);
}
return result;
}
}
相关文章推荐
- LeetCode 42 Trapping Rain Water
- LeetCode 42 Trapping Rain Water
- LeetCode42/11 Trapping Rain Water/Container With Most Water/Hist area**
- LeetCode-42-Trapping Rain Water 贪心或单调栈
- leetcode-42 Trapping Rain Water
- leetcode || 42、 Trapping Rain Water
- leetcode42_Trapping Rain Water
- leetcode 42:Trapping Rain Water
- [Leetcode 42] Trapping Rain Water
- leetcode question 42: Trapping Rain Water
- LeetCode-42:Trapping Rain Water
- leetcode(42) - Trapping Rain Water
- LeetCode(42) Trapping Rain Water
- Leetcode42 Trapping Rain Water
- [*leetcode 42] Trapping Rain Water
- LeetCode-42-Trapping Rain Water(C语言实现)
- LeetCode(42)Trapping Rain Water
- [leetcode-42]Trapping Rain Water(java)
- LeetCode(42)Trapping Rain Water
- LeetCode (42): Trapping Rain Water