題目:https://oj.leetcode.com/problems/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.
最簡單的想法當然是暴力遍歷,如果能走到下一個加油站就繼續不行就換一個開始結點進行遍歷。。。但是想着就算這個算法能夠AC也沒啥技術含量,沒什麼意思。所以還是上網看了一下別人的解題報告,果然找到了一個比較巧妙的解法。
這種解法基於一個條件:
如果以加油站i爲起點,汽車能夠從加油站i到達加油站i+1則gas[i] - cost[i]肯定要大於等於0。如果能夠到達第i + 2個加油站,那麼gas[i] - cost[i] + gas[i + 1] - cost[i + 1]肯定也要大於等於0.......所以如果從i出發到某節點是出現gas[i] - cost[i] + ...+gas[j] - cost[j] < 0則說明從加油站i不能到達加油站j,並且從j之前的任何加油站出發也不能到達加油站j(可以這樣想,如果汽車能夠從加油站i到加油站k,k位於i與j之間,那麼說明汽車到達k之後油箱裏面剩的油至少爲0,如果從i不能走到j,則從k也不能走到j),所以可以直接跳過i與j之間的加油站,測試從j+1出發能不能走到最後。
所以可以定義一個數組tmp[i] = gas[i] - cost[i]。用total計算tmp數組的總和。如果total>=0,則表明汽車是能夠繞一圈的,否則不能。
另外,還有一個問題困擾到我了,爲什麼能走到最後一個加油站,就能走一圈呢?(不是很明白==)
AC代碼:
<span style="font-size: 14px;">class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int len = gas.size();
//先求數組tmp = gas[i] - cost[i]
vector<int> tmp(len,0);
for(int i = 0;i < len;i++){
tmp[i] = gas[i] - cost[i];
}
//因爲如果車能從點i到點j則必須有從i到j的tmp之和大於0
//用sum記錄車能否開到結點i+1,如果sum < 0表示不行,則要從i + 1作爲下次的開始結點開始走
//total用來記錄車能否繞行一圈,如果total > 0表示可以
int sum = 0,total = 0,start = 0;
for(int i = 0;i < len;i++){
sum += tmp[i];
total += tmp[i];
if(sum < 0){
start = i + 1;
sum = 0;
}
}
if(total < 0) return -1;
else return start;
}
};</span>