题目
在一条环路上有 n
个加油站,其中第 i
个加油站有汽油 gas[i]
升。
你有一辆油箱容量无限的的汽车,从第 i
个加油站开往第 i+1
个加油站需要消耗汽油 cost[i]
升。你从其中的一个加油站出发,开始时油箱为空。
给定两个整数数组 gas
和 cost
,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1
。如果存在解,则 保证 它是 唯一 的。
示例 1:
输入: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。
示例 2:
输入: gas = [2,3,4], cost = [3,4,3]
输出: -1
解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。
解
①穷举法,超过时间范围
用例通过34/40
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// 必须按照顺序走下去
int[] start=new int[gas.length];
for(int i=0;i<gas.length;i++){
if(gas[i]<cost[i]){
// 如果该加油站需要消耗的大于等于能够补给的,则不能作为起点
start[i]=0;
}
else{
start[i]=1;
}
}
for(int i=0;i<gas.length;i++){
if(start[i]==1){
int index=(i+1)%(gas.length);
int have_gas=gas[i]-cost[i];
for(int j=0;j<gas.length-1;j++){
have_gas=have_gas+gas[index]-cost[index];
if(have_gas<0){
start[i]=0;
break;
}
index=(index+1)%gas.length;
}
if(have_gas >= 0){
return i;
}
}
}
return -1;
}
}
② 一次循环,运行时间2ms
代码借鉴gpt的结果,倒推为什么设置start=i+1的思路如下
假设从A作为起点,一直到C,从C到D的时候发现无法到达,根据这个情况往前倒推,最终可以得到结果:从A、B、C作为起点都无法到达D,故应该修改start为D,从D重新计算CurrentGas
结论:如果从A无法到达D,则从AD之间的任意一个加油站出发都无法到达D
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0; // 计算总的剩余油量
int currentGas = 0; // 计算当前的剩余油量
int start = 0; // 记录起始加油站的位置
for (int i = 0; i < gas.length; i++) {
totalGas += gas[i] - cost[i];
currentGas += gas[i] - cost[i];
if (currentGas < 0) {
// 如果当前剩余油量为负,说明无法从当前加油站出发到下一个加油站
// 所以起始位置应该设置为下一个加油站
start = i + 1;
currentGas = 0; // 重置当前剩余油量
}
}
// 如果总的剩余油量小于0,则无法完成一次循环
if (totalGas < 0) {
return -1;
} else {
return start;
}
}
}