leetcode134. Gas Station

来源:互联网 发布:哈登15 16赛季数据 编辑:程序博客网 时间:2024/04/20 21:46

134. 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.

Note:
The solution is guaranteed to be unique.

解法一

start先从0开始,如果到该供不应求(小于0),从该结点的下一个结点开始,然后再把之前亏损的加起来,判断是否能补完空缺。

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        if (gas == null || gas.length == 0 || cost == null || cost.length == 0) {            return -1;        }        int start = 0;        int cur = 0;        int total = 0;        for (int i = 0; i < gas.length; i++) {            cur += gas[i] - cost[i];            total += gas[i] - cost[i];            if (cur < 0) {                start = i + 1;                cur = 0;            }        }        if (total < 0) {            return -1;        } else {            return start;        }    }}

这里写图片描述

解法二

  1. 如果从一个加油站不能到达下一个加油站,那么之后的所有加油站都不能到
  2. 如果能走一圈,那么所有的gas之和肯定大于等于所有cost之和

所以,在进行遍历时,一方面要记录当前测试的加油站在哪,即start;另一方面要记录在到达start加油站之前缺少的gas之和是多少。

因此只要对所有加油站从标号0开始遍历一次,在遍历时,如果当前加油站不能到达下个加油站,那么start就标记为下个加油站(因为当前加油站对此后所有加油站都不能到);记录从标号0的加油站到标号为start的加油站所有缺少的gas之和need,遍历结束时,判断车厢剩的油是否大于等于从标号0的加油站到start之间缺少的gas之和need。

如果遍历一次结束时油箱剩的gas能大于等于need,说明剩的油可以补充汽车从0跑到start缺少的gas,故返回start;否则无解,返回-1.

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        if (gas == null || gas.length == 0 || cost == null || cost.length == 0) {            return -1;        }        int start = 0;        int cur = 0;        int need = 0;        for (int i = 0; i < gas.length; i++) {            cur += gas[i] - cost[i];            if (cur < 0) {                start = i + 1;                need += cur;                cur = 0;            }        }        if (cur + need < 0) {            return -1;        } else {            return start;        }    }}

这里写图片描述

1 0