题目:
算法思想:
1.如果总耗油量大于总加油量,那肯定是达到不了的,直接返回-1;
2.如果从某点出发,当前所剩油量小于0,表示达到不了,从该起点到该点中间所有路径应该都是不能达到的,直接跳过。
代码:
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0;
int totalCost = 0;
for (int i = 0; i < gas.length; i++) {
totalGas = totalGas + gas[i];
totalCost = totalCost + cost[i];
}
if (totalGas < totalCost) {
return -1;
}
int curGas = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
curGas = curGas - cost[i] + gas[i];
if (curGas < 0) {
curGas = 0;
start = i + 1;
}
}
return start;
}