Leetcode 42 Trapping Rain Water
2017-01-17 05:09
288 查看
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
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.
积水的问题。
首先有个类似的问题Leetcode 11 Container With Most Water
使用两个指针,每次移动小的一边
这个问题也非常类似。
设置左右两个指针,a,b.
每次比较对应数值大小,移动小的一边。
也就是最后ab相遇的地方就是柱子的最高值。
leftmax和rightmax其实是最高柱子两边第二高的部分
当当前位置的leftmax<rightmax 那么a对应的部分就可以储水 储水的量就是 leftmax-A[a] 反之亦然
如果说当前的柱子高度A[a]和leftmax相等,a这个地方就不能储水。
当ab任何一边到达最高柱子就不再移动,剩下移动的一边不断移动进行储水,出水量已第二高柱子为准。
public int trap(int[] A){
int a=0;
int b=A.length-1;
int max=0;
int leftmax=0;
int rightmax=0;
while(a<=b){
leftmax=Math.max(leftmax,A[a]);
rightmax=Math.max(rightmax,A[b]);
if(leftmax<rightmax){
max+=(leftmax-A[a]); // leftmax is smaller than rightmax, so the (leftmax-A[a]) water can be stored
a++;
}
else{
max+=(rightmax-A[b]);
b--;
}
}
return max;
}
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.
积水的问题。
首先有个类似的问题Leetcode 11 Container With Most Water
使用两个指针,每次移动小的一边
这个问题也非常类似。
设置左右两个指针,a,b.
每次比较对应数值大小,移动小的一边。
也就是最后ab相遇的地方就是柱子的最高值。
leftmax和rightmax其实是最高柱子两边第二高的部分
当当前位置的leftmax<rightmax 那么a对应的部分就可以储水 储水的量就是 leftmax-A[a] 反之亦然
如果说当前的柱子高度A[a]和leftmax相等,a这个地方就不能储水。
当ab任何一边到达最高柱子就不再移动,剩下移动的一边不断移动进行储水,出水量已第二高柱子为准。
public int trap(int[] A){
int a=0;
int b=A.length-1;
int max=0;
int leftmax=0;
int rightmax=0;
while(a<=b){
leftmax=Math.max(leftmax,A[a]);
rightmax=Math.max(rightmax,A[b]);
if(leftmax<rightmax){
max+=(leftmax-A[a]); // leftmax is smaller than rightmax, so the (leftmax-A[a]) water can be stored
a++;
}
else{
max+=(rightmax-A[b]);
b--;
}
}
return max;
}
相关文章推荐
- [leetcode 42] Trapping Rain Water
- LeetCode 42 Trapping Rain Water
- LeetCode---(42)Trapping Rain Water
- [LeetCode 42] Trapping Rain Water
- LeetCode_OJ【42】Trapping Rain Water
- leetcode[42]Trapping Rain Water
- LeetCode 42 - Trapping Rain Water
- [Leetcode 42, Hard] Trapping Rain Water
- Leetcode 42 Trapping Rain Water
- LeetCode 42 --- Trapping Rain Water
- leetcode hard模式专杀之42. Trapping Rain Water
- LeetCode 42 Trapping Rain Water
- Java [Leetcode 42]Trapping Rain Water
- LeetCode(42)--Trapping Rain Water
- [leetcode] Trapping Rain Water
- LeetCode Online Judge 题目C# 练习 - Trapping Rain Water
- leetcode - Trapping Rain Water
- [leetcode] Trapping Rain Water
- LeetCode Trapping Rain Water
- LeetCode-Trapping Rain Water