public class Solution {
public int trap(int[] height) {
int first = 0;
int last = height.length-1;
for(int i=0;i<height.length;i++){
if(height[i]!=0){first=i;break;}
}//找到开始的地方
for(int i=height.length-1;i>=0;i--){
if(height[i]!=0){last = i;break;}
}//找到最后的地方,防止最后是0
int count = 0;//水量
while(first<last){
if(height[first]<height[last]){
for(int i=first+1;i<last;i++){
if(height[i]<height[first]){//第一种情况,起点高度小于终点高度
count+=height[first] - height[i];
height[i] = height[first];
}//从结尾到起点,凡是比起点小的,都变成起点的高度,需要获得水量就是起点水量减去该点水量
}
for(int i=first+1;i<height.length;i++){
if(height[i]>height[first]){first=i;break;}//结束后,起点会往下走,找到比他要大的最近的一个点
first = i;
}
continue;
}else if(height[first] == height[last]){
//把中间给填平
for(int i=first+1;i<last;i++){
if(height[i]<height[first]){
count+=height[first] -height[i];
height[i] = height[first];
}
}
System.out.println(count);
//起点会找到最近的比他大的点,终点也会找到最近的比他大的点
for(int i=first+1;i<height.length;i++){
if(height[i]>height[first]){first=i;break;}
first =i;
}
for(int i=last-1;i>=0;i--){
if(height[i]>height[last]){last = i;break;}
last = i;
}
continue;
}else{
//和第一种情况相似,这是起点高度小于重点高度
for(int i=first+1;i<last;i++){
if(height[i]<height[last]){
count+=height[last] - height[i];
height[i] = height[last];
}
}
for(int i=last-1;i>=0;i--){
if(height[i]>height[last]){last=i;break;}
last = i;
}
continue;
}
}
return count;
}
}
42. Trapping Rain Water
最新推荐文章于 2022-01-25 23:54:30 发布