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