您的位置:首页 > 移动开发

leetcode_c++:trappint rain water(042)

2016-05-23 01:21 393 查看

题目

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.

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!

Subscribe to see which companies asked this question

算法

O(N)

为3*12的矩阵,两个1之间为水量;

#include<iostream>
#include<vector>
#include <algorithm>

using namespace std;

/*扫描3*12的矩阵的每一行,两个1之间为水量*/
class Solution {
public:
int trap(vector<int>& height) {
int maxi=0,peak=0,sum=0;
int n=height.size();

// get the max position
for(int i=0;i<n;i++)
if(height[maxi]<height[i])
maxi=i;

//first part:forward  to maxi
for(int i=0;i<maxi;++i){
if(height[i]<peak)
peak=height[i];
else
sum+=peak-height[i];
}

//second: 往后找

peak=0;
for(int i=n-1;i>maxi;--i){
if(height[i]>peak)
peak=height[i];
else
sum+=peak-height[i];

}

return sum;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: