# LeetCode | Gas Station（加油站）

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.

Note:
The solution is guaranteed to be unique.

``````class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
if(gas.size() != cost.size())
return -1;
res = -1;
vector<int> remainder;
for(int i = 0;i < gas.size();i++)
remainder.push_back(gas[i]-cost[i]);
FindIndex(remainder,0);
return res;
}
bool FindIndex(vector<int> &remainder,int index){
if(index >= remainder.size()){
return false;
}
int i;//写在外面
for(i = index;i < remainder.size();i++){
if(remainder[i] >= 0)   //要加等号[2] [2]
break;
}
if(i == remainder.size()){
int res = -1;
return false;
}

return Judge(remainder,i) || FindIndex(remainder,i+1);
}
bool Judge(vector<int> &remainder,int index){
int sum = 0;
for(int i = 0;i < remainder.size();i++){
sum += remainder[(index+i)%remainder.size()];
if(sum < 0)
return false;
}
res = index;
return true;
}
private:
int res;
};``````

``````class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int sum=0;
int total=0;
int start=0;
for(int i=0;i<gas.size();i++)
{
sum+=gas[i]-cost[i];
total+=gas[i]-cost[i];
if(sum < 0)
{
start=(i+1)%gas.size(); sum=0;
}
}

if(total <0)
return -1;
else
return start;
}
};``````

1：假设出发车站为0，初始化车内油量0
2：车内油量＝车站油量－消耗
3：如果车内油量大于0，车开到下一车站，否则出发车站前移一个车站

``````public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null) {
return -1;
}
// Note: The Solution object is instantiated only once and is reused by each test case.
int count = gas.length;

int n = 0;
int gasInCar = 0;
int begin = 0;
int end = 0;
int i = 0;
while (n < count - 1) {
gasInCar += gas[i] - cost[i];
if (gasInCar >=0) {//forward
end++;
i=end;
} else {
begin--;
if (begin < 0) {
begin = count - 1;
}
i = begin;
}

n++;
}

gasInCar += gas[i] - cost[i];

if (gasInCar >= 0) {
return begin;
} else {
return -1;
}

}
``````