leetcode_Gas Station

来源:互联网 发布:windows to go制作方法 编辑:程序博客网 时间:2024/06/03 22:51

描述:

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.

思路:

这是一个动态规划的题目,假设能跑完全程,最后邮箱中的油肯定还有剩余,由于是一个环形的路线,所以理论来讲,可以从任何地方开始。所以,可以用两个变量来表示这道题目,sum表示全程的油的剩余,而index来表示从何处开始。
1.从任何地方可以开始本次的行程,而sum+=gas[i]-cost[i],若sum<0,说明从index开始是不合适的,换成从i+1开始,直至结尾
2.若最后sum>=0,说明路线存在且以index为起点的路线为一个可行的路线。

代码:

public int canCompleteCircuit(int[] gas, int[] cost) {        int sum=0,tempSum=0,num=0,stationNum=0;        int len=gas.length;        for(int i=0;i<len;i++)        {            num=gas[i]-cost[i];            sum+=num;            tempSum+=num;            if(tempSum<0)            {                stationNum=(i+1)%len;                tempSum=0;            }        }        if(sum>=0)            return stationNum;        return -1;    }


0 0
原创粉丝点击