思路
用两个变量start和end记录浇水位置,当前剩余水量大于需要浇水量时,进行浇水并前进一步,否则需要返回加水(即重新灌满水罐的次数+1)
解题方法
用while(start<end)进行上述循环,循环结束时,如果start==end且Math.max(startwater,endwater)<plants[start]则重新灌满水罐的次数+1
Code
class Solution {
public int minimumRefill(int[] plants, int capacityA, int capacityB) {
int n=plants.length;
int start=0;
int startwater=capacityA;
int end=n-1;
int endwater=capacityB;
int ans=0;
while(start<end){
if(startwater>=plants[start]){
startwater=startwater-plants[start];
start++;
}else{
startwater=capacityA-plants[start];
start++;
ans++;
}
if(endwater>=plants[end]){
endwater=endwater-plants[end];
end--;
}else{
endwater=capacityB-plants[end];
end--;
ans++;
}
}
if(start==end&&Math.max(startwater,endwater)<plants[start])ans++;
return ans;
}
}