<leetcode> Gas station

来源:互联网 发布:淘宝联名信用卡怎么用 编辑:程序博客网 时间:2024/05/17 21:41

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.


思路来源于水中的鱼

新建一个油耗数组diff[], 赋值为diff[i]=gas[i]-cost[i] 若存在解,则证明diff[]的和为正值(总补给大于总消耗),若diff[]和为负值,证明无解(消耗大于补给)

设解为k(唯一),则diff[]中从k到diff.length-1的和为正值(可以从k走到最后), 并且对于其中任意一个点n,k到n的和均为正值(否则k无法到n)

设一个sum=sum+diff[i],当sum小于0的时候从当前位置从新开始计算(sum=0,start=i+1)直到找到一个k使k到(diff.size-1)的和为正值。如果没有返回-1;

找到k后同时需要确定是否有解(即k能否从length-1走到k(loop)),若diff[]和为正则证明有解,k为唯一解,若为负证明无解返回-1


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



0 0
原创粉丝点击