中心是抓住 sum(gas)一定 >= sum(cost) 才能跑完这一点来完成的
但是 加入了一个curr 来 选当前站点是否可以走完循环 如果cur< 0 则不可以 ,接着讲start 替换即可
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int total_tank = 0;
int curr_tank = 0;
int start = 0;
for (int i = 0; i < n; ++i) {
total_tank += gas[i] - cost[i];
curr_tank += gas[i] - cost[i];
if (curr_tank < 0) {
start = i + 1;
curr_tank = 0;
}
}
return total_tank >= 0 ? start : -1;
}
}
本文介绍了一种解决加油站问题的有效算法,关键在于确保总油量大于等于总消耗,并通过curr变量判断从哪个加油站开始能顺利绕一圈。算法首先计算所有加油站的油量与消耗之差,若累计油量小于0,则更新起始加油站并清零累计油量。
1368

被折叠的 条评论
为什么被折叠?



