[LeetCode]Gas Station

来源:互联网 发布:vb脚本怎么运行 编辑:程序博客网 时间:2024/06/06 00:44

题目分析

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.

现在有N个加油站形成环形,每个加油站储油gas[i]。现在有一辆车没有储油限制,并且它从加油站i到加油站i+1耗费油cost[i],问你能否找到一个加油站使其作为起点,你可以走完一圈。如果没有返回-1;

解题思路


由上图我们来进行分析,我们定义reminder表示从一个站点到下一个站点时剩余的油量,初始为0。
如果要满足题目要求,则应需要满足以下条件:
  1. 对于每一段路程,reminder>=0;
  2. 对于每一段路程,remainder + gas[j % len] >= cost[j % len];
  3. 若想完成一圈,则应从起始站点i环绕一圈再走到i,且满足上述的两点;
这时我们很容想到通过循环n次,并在每次循环中开始遍历,看能否满足上述3点。这样想是非常正确的,但是你是否觉得有点问题?
对,这样做会超时,为什么呢?
我们来考虑,如果从0到i走不通,在i处中断,那么从1、2、3、i-1到i能否走通呢?答案是否定的,仔细想明白这一点我们就可以简化循环,节省时间。具体请看代码。

代码

public int canCompleteCircuit(int[] gas, int[] cost) {        int len = gas.length;int remainder = 0;for (int i = 0; i < len; i++) {int j = i;while (j != len + i) {if (remainder >= 0 && remainder + gas[j % len] >= cost[j % len]) {remainder = remainder + gas[j % len] - cost[j % len];j++;} else {    i = j;break;}}if (j == len + i) {return i;}}return -1;    }


0 0