Gas Station

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.

思路:

  贪心算法 每一个进行尝试,尝试到j,如果测试不通过就继续i=j+1 或者往前搜索

我的代码:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length) return -1;
        int n = gas.length;
        int [] gap = new int[n];
        for(int i = 0; i < n; i++)
        {
            gap[i] = gas[i] - cost[i];
        }
        int last = n - 1;
        int right = 0;
        int sum = 0;
        while(right <= last)
        {
            sum += gap[right];
            if(sum < 0)
            {
                while(right <= last)
                {
                    sum += gap[last];
                    if(sum < 0)
                    {
                        last--;
                    }
                    else
                    {
                        right++;
                        last--;
                        break;
                    }
                }
            }
            else
                right++;
        }
        if(sum < 0) return -1;
        return (right) % n;
    }
}
View Code

他人代码:

  1. 从i开始,j是当前station的指针,sum += gas[j] – cost[j] (从j站加了油,再算上从i开始走到j剩的油,走到j+1站还能剩下多少油)
  2. 如果sum < 0,说明从i开始是不行的。那能不能从i..j中间的某个位置开始呢?既然i出发到i+1是可行的, 又i~j是不可行的, 从而发现i+1~ j是不可行的。
  3. 以此类推i+2~j, i+3~j,i+4~j 。。。。等等都是不可行的
  4. 所以一旦sum<0,index就赋成j + 1,sum归零。
  5. 最后total表示能不能走一圈。
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if (gas == null || cost == null || gas.length == 0 || cost.length == 0) {
            return -1;
        }
        int sum = 0;
        int total = 0;
        int index = -1;
        for(int i = 0; i<gas.length; i++) {
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(sum < 0) {
                index = i;
                sum = 0;
            }
        }
        return total < 0 ? -1 : index + 1;
    }
}
View Code

学习之处:

  • 这个思想是最重要的:如果sum < 0,说明从i开始是不行的。那能不能从i..j中间的某个位置开始呢?既然i出发到i+1是可行的, 又i~j是不可行的, 从而发现i+1~ j是不可行的。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4360061.html