【LeetCode 面试经典150题】134. Gas Station 加油站

134. Gas Station

题目大意

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays gas and cost, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique.

中文释义

沿着一条环形路线有 n 个加油站,第 i 个加油站有 gas[i] 单位的汽油。

你有一辆油箱无限的汽车,从第 i 个加油站到下一个(即第 i + 1 个)加油站需要消耗 cost[i] 单位的汽油。你从一个加油站开始旅行时油箱为空。

给定两个整数数组 gas 和 cost,如果你能顺时针方向绕环形路线走一圈,则返回起始加油站的索引,否则返回 -1。如果存在解决方案,它保证是唯一的。

Example

Example 1:

  • Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
  • Output: 3
  • Explanation:
    • 从加油站 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 作为起始索引。

Example 2:

  • Input: gas = [2,3,4], cost = [3,4,3]
  • Output: -1
  • Explanat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值