Lintcode187 solution 題解

【題目描述】

There areNgas 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.

Notice:The solution is guaranteed to be unique.

在一條環路上有N個加油站,其中第i個加油站有汽油gas[i],并且從第_i_個加油站前往第_i_+1個加油站需要消耗汽油cost[i]。

你有一輛油箱容量無限大的汽車,現在要從某一個加油站出發繞環路一周,一開始油箱為空。

求可環繞環路一周時出發的加油站的編號,若不存在環繞一周的方案,則返回-1。

【注】:數據保證答案唯一。

【題目鏈接】

www.lintcode.com/en/problem/gas-station/

【題目解析】

這題的意思就是求出從哪一個油站開始,能走完整個里程,并且這個結果是唯一的。

首先我們可以得到所有油站的油量totalGas,以及總里程需要消耗的油量totalCost,如果totalCost大于totalGas,那么鐵定不能夠走完整個里程。

如果totalGas大于totalCost了,那么就能走完整個里程了,假設現在我們到達了第i個油站,這時候還剩余的油量為sum,如果 sum + gas[i] - cost[i]小于0,我們無法走到下一個油站,所以起點一定不在第i個以及之前的油站里面(都鐵定走不到第i + 1號油站),起點只能在i + 1后者后面。

【參考答案】

www.jiuzhang.com/solutions/gas-station/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容