Gas Station
medium 原题链接:https://leetcode.com/problems/gas-station/
最后更新于
这有帮助吗?
medium 原题链接:https://leetcode.com/problems/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 in the clockwise direction, otherwise return -1.
Note:
If there exists a solution, it is guaranteed to be unique.
Both input arrays are non-empty and have the same length.
Each element in the input arrays is a non-negative integer.
Input: gas = [1,2,3,4,5] cost = [3,4,5,1,2]
Output: 3
Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.
乍一看是O(n^2)的问题,即对每个点进行模拟。。
事实上,可以设置两个变量,sum来判断当前的i的有效性;totoal则判断整个组是否有解。从gas的0起点开始,依次遍历,遇到gas-cost<0时候,break;直到到可以走通的一个完整的clockwise,不然就返回-1。
时间复杂度:O(n)
时间复杂度:O(1)
Explanation:
The main idea is that every time we go to the next station as far as possible (remained gas is bigger or equal to 0) until we can not (remained gas is less than 0). Then we must extend our start station to the "last station" ( the station before start station) to find a possible solution. Repeat these two steps until we have checked all stations(start == end).
We can travel around the circuit only if the remained gas is bigger or equal to 0!