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


题解:

不管从哪个点开始,能够绕一圈的充要条件是所有的gas[i]之和大于等于所有的cost[i]之和,只要这个条件满足,那么必然存在一个点,从该点出发,可以绕一圈。

剩下的问题就是怎么把这个点找出来,从第一个点开始,试探着往前走,并用一个sum变量统计当前邮箱中剩余的油量,如果在某一个点油量为负了,说明刚才走的路线不可行。那么记录当前点为startPoint,再从这一点重新往前走;如果到某一点油量又为负,那么舍弃刚刚走过的路线,记当前点为startPoint,再重新从当前点开始......直到走到终点的时候,通过判断所有gas[i]之和与cost[i]之和的大小,确定是否能够狗完成遍历。如果不可以,返回-1,否则返回最近一个startPoint(这个startPoint一定可行,因为其他的点都被尝试过并且排除了,而stratPoint一定存在,所以这个startPoint必然可行)。

代码如下:

 1 public class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int startPoint = -1;
 4         int currentSum = 0;
 5         int total = 0;
 6         
 7         for(int i = 0;i < gas.length;i++){
 8             total += gas[i] - cost[i];
 9             currentSum += gas[i] - cost[i];
10             if(currentSum < 0)
11             {
12                 currentSum = 0;
13                 startPoint = i;
14             }
15         }
16         
17         return total >= 0 ? startPoint+1:-1;
18     }
19 }
原文地址:https://www.cnblogs.com/sunshineatnoon/p/3850413.html