题目
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
分析
题目意思为在一个加油站能加gas[i]的油,前往下一个加油站消耗cost[i]的油,判断是否能环绕一圈
1.换站时满足油小于等于0,且导致油小于等于0的必定是上一个站
2.承上,换站是相当于一个新的起点,更新油箱的油,并让start=i.
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int g=gas.size();
int c=cost.size();
if(!g||!c||g!=c) return -1;
int sum=0,total=0,start=0;
for(int i=0;i<g;i++){
total+=gas[i]-cost[i];
if(sum<0){
sum=gas[i]-cost[i];
start=i;
}
else{
sum+=gas[i]-cost[i];
}
}
return total<0?-1:start;
}
};