链接
题目
在一条环路上有 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 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。
说明
gas.length == n
cost.length == n
1 <= n <= 10e5
0 <= gas[i], cost[i] <= 10e4
思路一(暴力)
我们可以用cost数组的每个元素对应的减去gas数组中对应的元素,得到油量剩余量remain数组,然后枚举每个起始位置,如果起始位置就没油或者中途油量为负,那么这个起始位置就不成立。
C++ Code
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n=gas.size();
if(n==1 && gas[0]>=cost[0]) return 0;
vector<int> remain(n,0);
int res=-1;
for(int i=0;i<n;i++) remain[i]=gas[i]-cost[i];
//枚举每个起点
for(int i=0;i<n;i++)
{
//对每个起点进行判断
int sum=0;
int flag=1;
if(remain[i]==0) continue;
for(int j=i;j<=i+n;j++)
{
sum+=remain[j%n];
if(sum<0) {flag=0;break;}
}
if(flag==1) return i;
}
return -1;
}
};
这个做法没问题,但会超时。
思路二(贪心)
无论从哪个点出发,油量的变化趋势都是一样的,如果假设油箱里的汽油可以为负数,找到最小的负数就是出发点。如下图所示:
C++ Code
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int cur_gas=0, min_gas=0, min_index=0;
for(int i = 0;i<n;i++)
{
cur_gas = cur_gas + gas[i] - cost[i];
if(cur_gas < min_gas)
{
min_gas = cur_gas;
min_index = i+1;
}
}
return cur_gas>=0 ? min_index:-1;
}
};