1. 程式人生 > >[leetcode]134. Gas Station加油站

[leetcode]134. Gas Station加油站

CA ise 如何 ring exists log public 積累 www

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 in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.
  • Both input arrays are non-empty and have the same length.
  • Each element in the input arrays is a non-negative integer.

Example 1:

Input: 
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3

Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 
4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.

題意:

給定一條環形路,上面有N個加油站。每個加油都有到達所需油量和可加油量。求能走完全程的出發站。

思路:

非常經典的一道題。可以轉換成求最大連續和做,但是有更簡單的方法。基於一個數學定理:

如果一個數組的總和非負,那麽一定可以找到一個起始位置,從他開始繞數組一圈,累加和一直都是非負的

(證明貌似不難,以後有時間再補)

有了這個定理,判斷到底是否存在這樣的解非常容易,只需要把全部的油耗情況計算出來看看是否大於等於0即可。

那麽如何求開始位置在哪?

註意到這樣一個現象:

1. 假如從位置i開始,i+1,i+2...,一路開過來一路油箱都沒有空。說明什麽?說明從i到i+1,i+2,...肯定是正積累。
2. 現在突然發現開往位置j時油箱空了。這說明什麽?說明從位置i開始沒法走完全程(廢話)。那麽,我們要從位置i+1開始重新嘗試嗎?不需要!為什麽?因為前面已經知道,位置i肯定是正積累,那麽,如果從位置i+1開始走更加沒法走完全程了,因為沒有位置i的正積累了。同理,也不用從i+2,i+3,...開始嘗試。所以我們可以放心地從位置j+1開始嘗試。

以上轉自 https://www.cnblogs.com/boring09/p/4248482.html

代碼:

 1 class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int start = 0; // 起點
 4         int tank = 0; // 當前油量
 5         int deficit = 0; //赤足
 6         for(int i = 0; i< gas.length; i++){
 7             tank = tank + gas[i]-cost[i];
 8             if(tank < 0){
 9                 start = i+1;
10                 deficit = deficit + tank;
11                 tank = 0;
12             }
13         }
14         return tank + deficit >=0 ? start : -1 ;   
15     }
16 }

[leetcode]134. Gas Station加油站