【LeetCode】Gas Station 解题报告

2023-06-14,,

【LeetCode】Gas Station 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/gas-station/#/description

题目描述:

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.

Ways

首先我尝试了暴力解决,时间复杂度O(n^2),可是有个case超时了。这就说明时间复杂度不能太高,应该很可能在O(n)量级,即遍历所有加油站一次就能解决。

然后我就参考了别人的方法。首先明白两点:

    如果从一个加油站不能到达下一个加油站,那么之后的所有加油站都不能到
    如果能走一圈,那么所有的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) {
int tank = 0;
int need = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
tank += gas[i] - cost[i];
if(tank < 0){
start = i + 1;
need += tank;
tank = 0;
}
}
return tank + need >=0 ? start : -1;
}
}

Date

2017 年 3 月 31 日

【LeetCode】Gas Station 解题报告的相关教程结束。

《【LeetCode】Gas Station 解题报告.doc》

下载本文的Word格式文档,以方便收藏与打印。