【leetcode】 gas-station 加油站問題

題目描述:

環形路上有n個加油站,第i個加油站的汽油量是gas[i]。你有一輛車,車的油箱可以無限裝汽油。從加油站i走到下一個加油站(i+1)花費的油量是cost[i],你從一個加油站出發,剛開始的時候油箱裏面沒有汽油。求從哪個加油站出發可以在環形路上走一圈。返回加油站的下標,如果沒有答案的話返回-1。

注意:答案保證唯一。

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.

問題分析:

1、通過所有加油站的汽油量總和減去花費油量總和,可以判斷是否可以在環形路上走一圈,如果不可以,那麼返回-1;

2、假設到達第i個加油站的剩餘油量爲sum,那麼加上第i個加油站的汽油量gas[i]再減去走到下一站(i+1)花費的油量cost[i],可判斷從第i個加油站是否可以到達下一個加油站;

3、如果當前位置不支持繼續前進,那麼換下一個加油站作爲出發點;

4、如果有解,那麼是唯一解,返回加油站的位置(從1開始計數)。

算法分析:

可以運用貪心的思想解決該問題,核心是start的尋找。從第一個加油站開始,如果遇到不符合要求,那麼從不符合要求位置的加油站開始,鑑於前面的計算,可知第一個加油站到該位置可達,如果從該位置出發可以走到終點說明可以在環形路上走一圈。算法時間複雜度爲O(n)。

編碼實現:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0, start = -1, total = 0;
		for( int i=0; i<gas.length; i++) {
			sum += gas[i]-cost[i];
			total += gas[i]-cost[i];
			if(sum<0) {
				sum = 0;
				start = i;
			}
		}
		return total>=0 ? start+1:-1;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章