Description:
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.
Link:
https://leetcode.com/problems/gas-station/description/
解題方法:
一開始用的是O(N^2)的brute force,不能AC。
于是換一種O(N的方法):
有題目可知:
1、在第i個加油站時,gas[i] - cost[i] >= 0意味著車子可以從這個加油站經過,并且tank里可能剩油或者為空。
2、如果我們任意選擇一個點start出發(也就是可以從第一個加油站出發),當走到A點時發現tank和A點的油加起來都不夠走過A點,那么意味著我們從start點到A點之前的任意一個點出發,都不可能走過A點。
3、當出現以上情況時,如果車子能夠循環跑一圈,意味著出發點必須在A點之后。此時應該把當前不夠的油記錄下來,讓tank重置為0,即以A點以后的點為start繼續跑,最后跑完(跑完最后一個加油站)看看tank里面剩下的油能不能把之前的坑填上,如果不能就返回-1,能就返回start。
Time Complexity:
O(N)
完整代碼:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
if(gas.size() == 0 || cost.size() == 0)
return -1;
int tank = 0, lack = 0, start = 0;
for(int i = 0; i < gas.size(); i++)
{
tank += gas[i] - cost[i];
if(tank < 0)
{
lack += tank;
start = i + 1;
tank = 0;
}
}
return lack + tank >= 0 ? start : -1;
}