LeetCode 题解工作台

加油站

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 给定两个整数数组 gas 和 cost ,如果你可以按顺序绕环路行驶一周…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们用 , 分别标记起点和终点,用 表示当前剩余汽油,而 表示当前行驶过的加油站数量。初始时,我们将起点设在最后一个位置,即 。 开始行驶,移动 。若发现当前剩余汽油小于 ,说明当前 作为起点不符合要求,我们将起点 循环左移,并且更新剩余汽油,直至剩余汽油是非负数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gascost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

 

示例 1:

输入: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。

示例 2:

输入: gas = [2,3,4], cost = [3,4,3]
输出: -1
解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。

 

提示:

  • n == gas.length == cost.length
  • 1 <= n <= 105
  • 0 <= gas[i], cost[i] <= 104
  • 输入保证答案唯一。
lightbulb

解题思路

方法一:从任意起点开始遍历

我们用 ii, jj 分别标记起点和终点,用 ss 表示当前剩余汽油,而 cntcnt 表示当前行驶过的加油站数量。初始时,我们将起点设在最后一个位置,即 i=n1i=n-1

开始行驶,移动 jj。若发现当前剩余汽油小于 00,说明当前 ii 作为起点不符合要求,我们将起点 ii 循环左移,并且更新剩余汽油,直至剩余汽油是非负数。

当行驶过的加油站数量达到 nn 时,结束行驶过程。若此时剩余汽油 ss 仍然小于 00,说明不存在这样的起点,返回 1-1。否则,返回起点 ii

时间复杂度 O(n)O(n),其中 nn 表示加油站的数量。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        i = j = n - 1
        cnt = s = 0
        while cnt < n:
            s += gas[j] - cost[j]
            cnt += 1
            j = (j + 1) % n
            while s < 0 and cnt < n:
                i -= 1
                s += gas[i] - cost[i]
                cnt += 1
        return -1 if s < 0 else i
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates a good understanding of greedy algorithms by proposing a solution based on the greedy choice paradigm.

  • question_mark

    The candidate explains invariant validation correctly, ensuring that they track gas levels and station indices effectively throughout the solution.

  • question_mark

    The candidate shows familiarity with optimization techniques, aiming to solve the problem in linear time with minimal extra space.

warning

常见陷阱

外企场景
  • error

    Failing to consider the case where the total gas is less than the total cost, which leads to an incorrect answer.

  • error

    Not correctly handling the circular nature of the route, which might cause the candidate to miss a valid starting point.

  • error

    Incorrectly assuming that it's always possible to start from any station and reach the end without first validating the total gas and cost.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the gas and cost arrays contain very large values, or the number of stations is extremely high?

  • arrow_right_alt

    How would you modify the approach to accommodate variable costs that change dynamically while traveling?

  • arrow_right_alt

    Can the problem be solved using a dynamic programming approach, and how would it compare to the greedy solution?

help

常见问题

外企场景

加油站题解:贪心·invariant | LeetCode #134 中等