码迷,mamicode.com
首页 > 移动开发 > 详细

[leetcode]Trapping Rain Water

时间:2014-08-08 12:30:45      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   for   

Trapping Rain Water

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.

bubuko.com,布布扣

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! 

算法思路:

短板效应,蓄水量与桶的短板相关。求出height数组中的最长板,然后从两端向长板迭代,遇到更短的则求出蓄水量,遇到较长的,则更新边缘。

代码如下:

 1 public class Solution {
 2     public int trap(int[] height) {
 3         if(height == null || height.length < 3) return 0;
 4         int max = 0;
 5         for(int i = 0; i < height.length;i++){
 6             if(height[i] > height[max]) max = i;
 7         }
 8         int high = 0,res = 0;
 9         for(int i = 0; i < max; i++){
10             if(height[i] < height[high]){
11                 res += height[high] - height[i];
12             }else if(height[i] > height[high]){
13                 high = i;
14             }
15         }
16         high = height.length - 1;
17         for(int i = height.length - 1; i > max; i--){
18             if(height[i] < height[high]){
19                 res += height[high] - height[i];
20             }else if(height[i] > height[high]){
21                 high = i;
22             }
23         }
24         return res;
25     }
26 }

具体算法分析可以参考这里

 

[leetcode]Trapping Rain Water,布布扣,bubuko.com

[leetcode]Trapping Rain Water

标签:style   blog   http   color   os   io   strong   for   

原文地址:http://www.cnblogs.com/huntfor/p/3898901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!