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

leetcode Trapping Rain Water

时间:2015-05-16 17:48:03      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

无脑写代码代码(TLE):

技术分享
 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 int findLeft(int i, vector<int> height)
 7 {
 8     int t = i-1;
 9     while ((t+1<height.size())&&t >= 0)
10     {
11         if (height[t] > height[t + 1])
12             t--;
13         else
14             break;
15     }
16     return t + 1;
17 }
18 
19 int findRight(int i, vector<int> height)
20 {
21     int t = i + 1; 
22     while ((t-1>=0)&&t < height.size())
23     {
24         if (height[t] > height[t - 1])
25             t++;
26         else
27             break;
28     }
29     return t - 1;
30 }
31 
32 int trap(vector<int>& height) 
33 {
34     int L = height.size();
35     int sum = 0;
36     for (int i = 1; i < L-1; i++)
37     {
38         int left = findLeft(i, height);
39         int right = findRight(i, height);
40         if (left < i&&right > i)
41         {
42             int high = height[left] < height[right] ? height[left] : height[right];
43             for (int j = left+1; j < right; j++)
44             {
45                 sum = sum + high - height[j];
46             }
47         }
48     }
49     return sum;
50 }
51 
52 int main()
53 {
54     vector<int> height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
55     cout << trap(height) << endl;
56 }
View Code

 

leetcode Trapping Rain Water

标签:

原文地址:http://www.cnblogs.com/chaiwentao/p/4508064.html

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