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)绕一个有n个加油站点的环形路径上行驶。在加油点i可以加油gas[i],而到下一个目的地需要消耗cost[i]。求问是否存在一个起始加油点,可以让汽车走完全程。
分析
此题就是我们统计当前汽车的油量为total时,total += gas[i]- cost[i],使得total恒大于0,则这个起点有效。
1、首先想到的是 O ( N 2) 的解法,对每个点进行模拟,超时。
2、O( N) 的解法是,设置两个变量, sum表示起点为station时当前的总油量; total则为全程的总油量,如果total不小于0,则返回通过sum得到起点的下标station;如果total小于0,则返回 -1。
//方法一:O( N) 的解法是,设置两个变量,sum表示起点为station时当前的总油量;total则为全程的总油量,如果total不小于0,则返回通过sum得到起点的下标station;如果total小于0,则返回 -1。 //时间复杂度 O(n) ,空间复杂度 O(1) class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int total = 0; int station = 0; for(int i = 0, sum = 0; i < gas.size(); i++) { sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if(sum < 0) { station = i + 1; //起点位置 sum = 0; } } return total < 0 ? -1 : station; } };
//方法:超时, O (N^2) 的解法,对每个点进行模拟 class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int sum = 0; for(int i = 0; i < gas.size(); i++) { sum = 0; for(int j = i; j < gas.size(); j++) { sum += gas[j] - cost[j]; if(sum < 0) break; } if(sum < 0) continue; for(int j = 0; j < i; j++) { sum += gas[j] - cost[j]; if(sum < 0) break; } return i; } return -1; } };