zoukankan      html  css  js  c++  java
  • LeetCode 134. Gas Station

    134. Gas Station

    Description Submission Solutions Add to List

    • Total Accepted: 77911
    • Total Submissions: 271464
    • Difficulty: Medium
    • Contributors: Admin

    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.

    【题目分析】

    给定一圈加油站,每个加油站都有一定的存油量,并且给定从上个加油站行驶到下个加油站的耗油量。问是否存在这样一个起始点,从这个点出发可以绕着所有的加油站行驶一圈。

    【思路】

    • If car starts at A and can not reach B. Any station between A and B
      can not reach B.(B is the first station that A can not reach.)
    • If the total number of gas is bigger than the total number of cost. There must be a solution.

    上面两句话的意思是:如果从A加油站不能到达B加油站,那么从AB之间的任何一个加油站出发都不能到达B。如果所有加油站的存油量大于绕行一圈的总耗油量,那么必定存在这样一个起始点,从这个点出发可以绕行所有的加油站一圈。

    初始时,油箱中的油量为0,我们记tank = 0

    从第一个油站出发:

    此时,油量为 tank += gas[0] - cost[0]
    如果tank > 0,说明我们可以到达下一个油站。

    到达油站 i 时:

    此时,油量为 tank += gas[i] - cost[i]

    • 如果tank >= 0,可以到达下一个油站,继续往下走。
    • 可是,如果 tank < 0呢?

      这时,我们不可能到达下一个油站(i + 1)了。
      并且,假设我们是从 begin 出发的,不仅从 begin 到不了油站 i + 1,并且从 begin 到 i 之间的任何一个油站出发都不可能到达油站 i + 1

      因此,我们需要把起点设置为油站 i + 1,油箱清空,重新开始往下走。

    最终,begin 总是会指向一个有可能走完一圈的开始地点。

     下面的代码实现了这样一个过程,如果发现从某个点不能到达下一个点,那么我们就修正起始点,并且这个过程中加油与消耗的差值记录下来,当遍历完所有加油站时,如果最后油有剩余,那个我们选择的最后一个出发点就是我们求的那个点。

     1 public class Solution {
     2     public int canCompleteCircuit(int[] gas, int[] cost) {
     3         int tank = 0, start = 0, total = 0;
     4         
     5         for(int i = 0; i < gas.length; i++) {
     6             if((tank = tank+gas[i]-cost[i]) < 0) {
     7                 start = i+1;
     8                 total += tank;
     9                 tank = 0;
    10             }
    11         }
    12         return (tank + total) < 0 ? -1 : start;
    13     }
    14 }
     
  • 相关阅读:
    Python动态展示遗传算法求解TSP旅行商问题
    MOEAD算法中均匀权向量的实现---Python
    HDU 5294 多校第一场1007题 最短路+最小割
    POJ 3261 Milk Patterns sa+二分
    HDU 4292 FOOD 2012 ACM/ICPC Asia Regional Chengdu Online
    CodeForces 201A Clear Symmetry
    POJ 1679 The Unique MST 确定MST是否唯一
    POJ 3268 Silver Cow Party 最短路 基础题
    POJ 2139 SIx Degrees of Cowvin Bacon 最短路 水題
    POJ2229 Sumsets 基礎DP
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6399363.html
Copyright © 2011-2022 走看看