LeetCode:Trapping Rain Water
2014-04-09 10:08
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.
看到这个题目,A[I]存储的水量主要取决于其左边最大值和右边最大值两个值的最小值minh,如果A[I]<minh,则存储水量为minh-A[i].因此想到用一个数组记录A[I]左边所有值的最大值,从右边往左边加过去,最终返回存储水量。
public class Solution {
public int trap(int[] A) {
if(A.length<=2)return 0;
int [] leftMaxHeight=new int[A.length];
leftMaxHeight[0]=0;
int maxh=A[0],len=A.length;
for(int i=1;i<A.length;i++)
{
leftMaxHeight[i]=maxh;
if(maxh<A[i])maxh=A[i];
}
int right=A[len-1],left,sum=0;
for(int i=len-2;i>0;i--)
{
left=leftMaxHeight[i];
int minh=Math.min(right,left);
if(minh>A[i])sum+=minh-A[i];
if(right<A[i])right=A[i];
}
return sum;
}
}
相关文章推荐
- LeetCode: Trapping Rain Water 解题报告
- Leetcode题目之"Trapping Rain Water"
- leetcode 42 Trapping Rain Water
- 【LeetCode】Trapping Rain Water 2013年美团网校园招聘研发工程师笔试题
- leetcode 91: Trapping Rain Water
- [Leetcode]Trapping Rain Water
- leetcode-42 Trapping Rain Water
- LeetCode 407: Trapping Rain Water II
- leetcode: Trapping Rain Water
- leetcode 407. Trapping Rain Water II
- LeetCode42——Trapping Rain Water
- Leetcode刷题记——Trapping Rain Water(捕获雨水)
- [LeetCode]Trapping Rain Water,解题报告
- [LeetCode]42 Trapping Rain Water
- Leetcode—— trapping-rain-water
- leetcode42_Trapping Rain Water
- LeetCode:Trapping Rain Water
- leetcode 91: Trapping Rain Water
- leetcode || 42、 Trapping Rain Water
- [leetcode] Trapping Rain Water