lintcode--加油站

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

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

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

 注意事項

數據保證答案唯一。

樣例

現在有4個加油站,汽油量gas[i]=[1, 1, 3, 1],環路旅行時消耗的汽油量cost[i]=[2, 2, 1, 1]。則出發的加油站的編號爲2。



/*
其實只要總的汽油量要大於總的消耗量,那麼肯定是有解的,可以從頭遍歷起,
什麼時候汽油量小於消耗量了,就假設從下一個點重新開始。
*/


public class Solution {
   public static int canCompleteCircuit(int[] gas, int[] cost) 
   {
        int cur = 0;  
        int totalGas = 0;  
        int totalCost = 0;  
        int start = 0;  
        for(int i=0;i<gas.length;i++)  
        {  
            cur +=gas[i]-cost[i];  
            totalGas+=gas[i];  
            totalCost+=cost[i];  
            if(cur<0)  
            {  //編號
                start = i+1;  
                cur = 0;  
            }  
        }
        //整體比較
        if(totalGas>=totalCost)  
            return start;  
        return -1;  
   }
}

發佈了124 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章