leetcode No42. Trapping Rain Water
來源:程序員人生 發(fā)布時(shí)間:2016-11-28 13:31:15 閱讀次數(shù):2929次
Question:
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!
數(shù)組元素代表高度,如圖所示,求能裝多少水
Algorithm:
分別從左右兩邊向最高點(diǎn)逼近,只在元素小的1邊地方儲水。由左側(cè)向最高點(diǎn)逼近時(shí),設(shè)左側(cè)當(dāng)前的最大值leftmax,當(dāng)前遍歷到i,如果leftmax
> A[i]; sum += (leftmax- A[i]);否則,currentMax = i,此條帶沒法儲水;由右側(cè)逼近最高點(diǎn)類似左側(cè)。
Accepted Code:
class Solution {
public:
int trap(vector<int>& height) {
int left=0;
int right=height.size()⑴;
int leftmax=0; //左側(cè)最大值
int rightmax=0; //右側(cè)最大值
int res=0; //結(jié)果
while(left<=right)
{
if(height[left]<=height[right])
{
if(height[left]>leftmax)
leftmax=height[left];
else
res+=leftmax-height[left];
left++;
}
else
{
if(height[right]>rightmax)
rightmax=height[right];
else
res+=rightmax-height[right];
right--;
}
}
return res;
}
};
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈