思路:
1.首先介紹一個定理,如果一個整數序列累加和非負,那麼一定可以找到一個起點,以該起點開始的序列累加和都非負。
2.由1知,只要gas累加和>=cost累加和 解一定存在,反之,一定無解
3.進行一次遍歷,totalGas記錄每個加油站gas[i]-cost[i]的和,curGas記錄當前油箱油量,startLoc記錄符合要求的起點加油站,所以知道當curGas[i]
< 0時,一定不能以i之前的加油站爲起點,此時油量需要重置爲0,起點startLoc要走到下一個加油站。依次類推,到末尾看totalGas是否>=0,如果是,則startLoc爲答案;反之,則說明gas數組總和小於cost數組總和,不存在解,返回-1.
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int totalGas, curGas;
totalGas = curGas = 0;
int beginLoc = 0;
for (int i = 0; i < gas.size(); i++) {
totalGas += gas[i] - cost[i];
curGas += gas[i] - cost[i];
if (curGas < 0) {
beginLoc = i + 1;
curGas = 0;
}
}
if (totalGas >= 0) //等於0不能忘記
return beginLoc;
return -1;