首页 > 代码库 > [leetcode] Gas Station
[leetcode] Gas Station
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, otherwise return -1.
Note:
The solution is guaranteed to be unique.
思路:
从第0个点开始,遍历容器。用一个变量remain记录经过每个点后邮箱内剩余的油量。如果计算第i点的remain<0,则说明无法从第i点开出,因为无法到达下一个点。于是只能重新选择起点。(这个起点一定不是在上一个起点与i点之间的某一点。可以这么证明,假设上一个起点是t,第i点时remain<0,有一点j位于t和i之间,那么t到达j的时候这一点的remain>=0,而如果将起点定在j点,有remain=0,所以到第i点时仍然会有remain<0。)
于是题目简化了,不用所有的点都当成起点进行遍历。如果发现到第i个点时remain<0,那么下一个起点就是i+1,一直到能够循环一圈的或者起点大于给定容器的容量。
题解:
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int start = 0; int remain = 0; int n = gas.size(); int i=0; while(start<n && i<start+n) { if(i<n) remain = remain+gas[i]-cost[i]; else remain = remain+gas[i-n]-cost[i-n]; if(remain<0) { start = i+1; remain = 0; } i++; } if(start>=n) return -1; return start; }};
[leetcode] Gas Station