这道题和之前腾讯的笔试题刷木板挺像的,不过这个更简单,这个就相当于短板效应,而刷木板那道题和刷栅栏相同,考虑的情况较多;
这道题一开始的思路就是从一面找;如果后面的小于前面的就加上差值,但是没考虑只有一个柱子的时候;
错误:
public int trap(int[] height) {
if(height==null||height.length==0){
return 0;
}
int []dp=new int[height.length];
for(int i=1;i<height.length;i++){
if(height[i]<height[i-1]){
dp[i]=dp[i-1]+(height[i-1]-height[i]);
}else{
dp[i]=dp[i-1];
}
}
return dp[height.length-1];
}
看了题解确实应该从两边找,有点贪心选择吧;
先找到最高的木头top,然后双指针向top遍历,两头开花;
从左边找的时候如果下一个大于最大值则res+=差值;
从右边找也是如果大于最大值则res+=差值;
就上题我们可以看到是 1 +1+ 2+ 1+ 1;
正解:
public int trap(int[] height) {
if(height==null||height.length==0){
return 0;
}
int len=height.length;
int maxIndex=0;
for(int i=0;i<len;i++){
if(height[i]>height[maxIndex]){
maxIndex=i;
}
}
int left=0,right=len-1,res=0;
for(int i=left;i<maxIndex;i++){
if(height[i]>=height[left]){
left=i;
}else{
res+=height[left]-height[i];
}
}
for(int i=right;i>=maxIndex;i--){
if(height[i]>height[right]){
right=i;
}else{
res+=height[right]-height[i];
}
}
return res;
}