更新:发现自己的代码运行时间达到了864ms,实在是太长了,稍后补充高票解法
自己第一次尝试写的代码通过314/315个案例,最后一个案例超时,最后一个案例的高度都在1千以上,所以每次向上上移一个单位是不够的(思想写在代码的注释里)
第一次代码:
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()<=2)
return 0;
//思想是每循环一层,所有存在的高度都减1,这样一次循环只统计当前层的雨滴数,当前层的雨滴数就是最左端到最右端,为0的数量
int ans;
int i = 0;
while(height[i]==0){
++i;
}
int j = height.size()-1;
while(height[j]==0){
--j;
}
while(i<j){
caculateRain(height,i,j);
while(height[i]==0){
++i;
}
while(height[j]==0){
--j;
}
}
ans = tempsum;
return ans;
}
private:
int tempsum = 0; //暂存结果
void caculateRain(vector<int>& height,int i,int j){
for(int index=i;index<=j;++index){
if(height[index]!=0){
--height[index];
}
else{
++tempsum;
}
}
}
};
第二次在之前的基础上,每次上移所有柱状高度中的最小值,通过两次循环,第一次循环获得最小值,第二次循环(若高度不为0就减去最小值高度,若高度为0就加上最小值到雨滴数中),代码AC,代码唯一的缺陷就是统计完雨滴数后,原数组无法保持原状。
第二次代码:
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()<=2)
return 0;
int ans;
int i = 0;
while(height[i]==0){
++i;
}
int j = height.size()-1;
while(height[j]==0){
--j;
}
while(i<j){
caculateRain(height,i,j);
while(height[i]==0){
++i;
}
while(height[j]==0){
--j;
}
}
ans = tempsum;
return ans;
}
private:
int tempsum = 0; //暂存结果
void caculateRain(vector<int>& height,int i,int j){
//采用两次循环来降低时间复杂度
int min = INT_MAX;
for(int index=i;index<=j;++index){
if(height[index]!=0&&height[index]<min){
min = height[index];
}
}
for(int index=i;index<=j;++index){
if(height[index]!=0){
height[index] -= min;
}
else{
tempsum += min;
}
}
}
};