134. 加油站
小于 1 分钟
134. 加油站中等
解法:遍历数组,同时加 gas[i]
,减 cost[i]
,得到最小值的索引的下一个即为答案
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int spare = 0;
int minSpare = Integer.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < len; i++) {
spare += gas[i] - cost[i];
if (spare <= minSpare) {
minSpare = spare;
minIndex = i;
}
}
return spare < 0 ? -1 : (minIndex + 1) % len;
}
}
Powered by Waline v2.15.5