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

Trapping Rain Water

2016-03-16 20:24 260 查看
Given n[/i] 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[/b] for contributing this image!

来源: <https://leetcode.com/problems/trapping-rain-water/>
分析空间复杂度O(n)对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;2. 从右往左扫描一遍,对于每个柱子,求最大右值;3. 再扫描一遍,把每个柱子的面积并累加。
class Solution {

public:

int trap(vector<int>& height) {

int length=height.size();

int *max_left=new int[length]();

int *max_right=new int[length]();


for(int i=1;i<length;i++){

    max_left[i]=max(max_left[i-1],height[i-1]);

    max_right[length-i-1]=max(max_right[length-i],height[length-i]);

}


int sum=0;

for (int i=0;i<length;i++){

    int h=min(max_left[i],max_right[i]);

    if(h>height[i])

sum+=h-height[i];

}

delete[]max_left;

delete[]max_right;

return sum;

}

};

[/code]
也可以,该方法空间复杂度O(1)1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;2. 处理左边一半;3. 处理右边一半。
class Solution {

public:

int trap(vector<int>& height) {

int max = 0; // 最高的柱子,将数组分为两半

int n=height.size();

for (int i = 0; i < n; i++)

    if (height[i] > height[max]) max = i;

int water = 0;

for (int i=0,peak=0;i<max;i++){

    if(peak<height[i])peak=height[i];

    else

water+=peak-height[i];

}    

for(int j=n-1,peak=0;j>max;j--){

    if(peak<height[j])peak=height[j];

    else

water+=peak-height[j];

}


return water;       

}

};

[/code]

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