把問題簡單化的話
第一次想就呈現這邏輯
result=0;
s=0;
e=height.length-1;
while(s<e){
if(height[s] <= height[e]){
int current=height[s];
if(height[++s]<current){
result=current-height[s];
}
} else {
int current=height[e];
if(height[--e]<current){
result=current-height[e];
}
}
}
正確解法:
class Solution {
public int trap(int[] height) {
int result = 0;
int start = 0;
int end = height.length - 1;
while (start < end) {
if (height[start] <= height[end]) {
int current = height[start];
while (height[++start] < current) {//多個空白
result += current - height[start];
}
} else {
int current = height[end];
while(height[--end] < current) {
result += current - height[end];
}
}
}
return result;
}
}
留言列表