题目链接https://leetcode-cn.com/problems/trapping-rain-water/submissions/题目:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.
思路:
一开始想先写一个暴力算法,但是发现连暴力算法都花了好长时间debug,原因是没有考虑特殊情况和理解题目含义。
后来想到了利用动态规划的思想,建立两个数组分别记录某个位置能储存水的最大体积,两个数组分别从左边和右边开始遍历得到。优化前对于每一个位置都向后进行判断,复杂度为O(),优化后省略了这一个过程,只需要记录目前所遍历过的高度中最高的高度即可,复杂度为O(n)。
题解:
class Solution {
public:
int trap(vector<int>& height) {
int i,j, curmax=0;
int len=height.size(), answer=0;
vector<int> ltor(len,0);
vector<int> rtol(len,0);
for(i=0;i<len;i++){
curmax=max(curmax,height[i]);
ltor[i]=max(ltor[i],curmax-height[i]);
}
curmax=0;
for(i=len-1;i>=0;i--){
curmax=max(curmax,height[i]);
rtol[i]=max(rtol[i],curmax-height[i]);
}
`
/* counting answer and the checking part */
for(int i=0;i<len;i++){
cout<<rtol[i]<<' ';
answer+=min(rtol[i],ltor[i]); // answer是两个数组的交集部分
} cout<<endl;
for(int i=0;i<len;i++) cout<<ltor[i]<<' ';
return answer;
}
};
优化前的 方法:
for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
if(height[i]>height[j])
ltor[j]=max(ltor[j],height[i]-height[j]);
else break;
}
}
for(int i=len-1;i>=0;i--){
for(int j=i-1;j>=0;j--){
if(height[i]>height[j])
rtol[j]=max(rtol[j],height[i]-height[j]);
else break;
}
}
总结:
一道看似简单的题目,却连暴力算法都花了很长时间都没写好,可见我的代码能力需要增强,要认真审题,同时注意到题目的细节要求。最后对于代码的优化也要下足功夫!