题目传送: ​​https://leetcode.cn/problems/gas-station/​

运行效率

Leetcode134. 加油站_动态规划


思路:​​https://leetcode.cn/problems/gas-station/solution/tan-xin-dong-hua-tu-jie-dai-ma-jian-ji-b-na6b/​

代码如下:

class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// 要想能跑完一圈,那首先要保证 总油量 > 总路程
// 思路 :首先判断总油量是否小于总油耗、如果是,则肯定不能走一圈。如果否,那肯定能跑一圈。
// 接下来就是循环数从第一个站开始,计算每一站剩余的油量,如果油量为负了,就以这个站为起点从新计算。
// 如果到达某一个点为说明起点到这个点中间的所有站点都不能到达该点。
// 总油量
int totalGas = getSum(gas);
// 总路程
int totalCost = getSum(cost);
if (totalCost > totalGas) {
return -1;
}
// 记录当前油量
int currentGas = 0;
// 记录符合条件的起始位置
int start = 0;
for (int i = 0; i < gas.length; i++) {
// 如果大于等于0,那说明可以到达第i+1个位置
if (currentGas + gas[i] - cost[i] >= 0) {
currentGas = currentGas + gas[i] - cost[i];
} else { // 如果小于0,说明不能到达第i+1个位置
//那就从下一个开始点进行
start = i + 1;
currentGas=0;
}
}
return start;
}

public int getSum(int[] array) {
int sum = 0;
for (int item : array) {
sum += item;
}
return sum;
}
}