码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 42

时间:2016-04-29 07:05:30      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 1 #include<stdio.h>
 2 
 3 int trap( int* height, int heightSize ){
 4 
 5     int left = 0;
 6     int right = heightSize - 1;
 7     int middle = 0;
 8     int water = 0;
 9 
10     while( left < right ){
11 
12         if( height[left] < height[right]){
13             middle = middle > height[left] ? middle : height[left];
14             water = water + middle - height[left];
15             left ++;
16         }else{
17             middle = middle > height[right] ? middle : height[right];
18             water = water + middle - height[right];
19             right --;
20         }
21     }
22     printf("Water is %d\n", water);
23     return water;
24 }
25 
26 int main(){
27     int height[] = {0,1,0,2,1,0,1,3,2,1,2,1};
28     int heightSize = 12;
29     trap( height, heightSize );
30     return 0;
31 }

 

LeetCode 42

标签:

原文地址:http://www.cnblogs.com/Juntaran/p/5444967.html

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