【LeetCode】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.

【題意】

環形路線上有N個加油站,每個加油站有汽油gas[i],從每個加油站到下一站消耗汽油cost[i],問從哪個加油站出發能夠回到起始點,如果都不能則返回-1(注意,解是唯一的)。

【Java代碼】(O(n^2)

[java] view plain copy
  1. public class Solution {  
  2.     public int canCompleteCircuit(int[] gas, int[] cost) {  
  3.         //依次從每一個加油站出發  
  4.         for (int i = 0; i < gas.length; i++) {  
  5.             int j = i;  
  6.             int curgas = gas[j];  
  7.               
  8.             while (curgas >= cost[j]) { //如果當前的汽油量能夠到達下一站  
  9.                 curgas -= cost[j];      //減去本次的消耗  
  10.                   
  11.                 j = (j + 1) % gas.length; //到達下一站  
  12.                 if (j == i) return i;   //如果回到了起始站,那麼旅行成功  
  13.                   
  14.                 curgas += gas[j];       //到下一站後重新加油,繼續前進  
  15.             }  
  16.         }  
  17.         return -1;  
  18.     }  
  19. }  


【Java代碼】(O(n)

[java] view plain copy
  1. public class Solution {  
  2.     public int canCompleteCircuit(int[] gas, int[] cost) {  
  3.         int sum = 0;  
  4.         int total = 0;  
  5.         int j = -1;  
  6.         for (int i = 0; i < gas.length; i++) {  
  7.             sum += gas[i] - cost[i];  
  8.             total += gas[i] - cost[i];  
  9.             if(sum < 0) {   //之前的油量不夠到達當前加油站  
  10.                 j = i;  
  11.                 sum = 0;  
  12.             }  
  13.         }  
  14.         if (total < 0return -1;    //所有加油站的油量都不夠整個路程的消耗  
  15.         else return j + 1;  
  16.     }  
  17. }  


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