LeetCode Gas Station

来源:互联网 发布:网络访问控制 编辑:程序博客网 时间:2024/06/07 09:25

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.

思路分析:这题O(n^2)的解法容易想到,可以从零开始,不断试探向后面走,如果发现油量为负数,则改变起点为1,以此类推。但是这种解法会超时。这题有O(n)的解法,也就是采用双指针的思路,用i来标记当前的start point,j表示当前car到达的station,用sum来表示car剩下多少油量,那么从i开始,j是当前station的指针,sum += gas[j] – cost[j] (从j站加了油gas[j],再算上从i开始走到j剩的油sum,减去从j走到j+1的油耗cost[j],这里是试探是否能走到j+1)。如果sum < 0,就说明从i开始是不行的,需要更新start point i。那能不能从i到j中间的某个位置开始呢?假设能从k (i <=k<=j)走,由于sum[i..j] < 0,如果sum[k..j] >=0,说明sum[i..k – 1]<0,那从i开始到k肯定无法到达,也就是说,从k出发,肯定是没有办法回到k的(至少i到k无法走)。所以一旦sum<0,应该把i赋成j + 1,sum归零。最后用total表示能不能走一圈。对于环状数组或者链表,经常可以用双指针的思路得到巧妙的解法,类似的题目还有判断一个链表是否存在circle,也可以用双指针的思路得到O(n)的解法。

这题参考了这个题解,需要更加深入思考反复理解。

AC Code

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int i = 0;        int j = 0;        int sum = 0;         int total = 0;                while(j < gas.length){            int leftGas = gas[j] - cost[j];            if(sum + leftGas < 0){                i = j + 1;                sum = 0;            } else {                sum += leftGas;            }            j++;            total += leftGas;        }         if(total >= 0) return i;        else return -1;          }};


0 0