
正文
Gas Station [LeetCode]
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
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.
Solution:
The brute force solution costs O(n^2), I find a O(n) and one round solution. If gas[i] >= cost[i], then I mark it, and calcuate the gas in tank along next node, if it is less than zero, then restart search.
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int curr_gas = ;
int idx = -;
int tmp_gas = ;
for(int i = ; i < gas.size(); i ++) {
curr_gas += gas[i] - cost[i];
if( idx != -)
tmp_gas += gas[i] - cost[i];
if(tmp_gas < ) {
idx = -;
tmp_gas = ;
}
if(gas[i] - cost[i] >= && idx == -) {
idx = i;
tmp_gas += gas[i] - cost[i];
}
}
if(curr_gas >= )
return idx;
else
return -;
}







