134. Gas Station(加油站)
题目链接
https://leetcode.com/problems/gas-station/description/
题目描述
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.
题目分析
这道题目很容易想到直观的算法:以每一个点作为出发点,尝试是否能走完一圈;若均不能,则没有。时间复杂度为O(n2)。
实际上经过分析我们可以发现:若以i
为出发点,走到j
时无法走到下一个点。对于在i
和j
中的任意一点k
,走到k点时剩余油量一定是大于等于0
的。所以,如果从i
为出发点最多只能走到j
,那么从k
也最多只能走到j
。所以若以i
为出发点无法走完一圈时,i
到j
之间的点都可以排除。时间复杂度为O(n)。
方法一:暴力
算法描述
从第1个点到最后一个点,以每一个点作为出发点:
若走到某一个点时不能走到下一个点,则尝试下一个出发点
若走完一圈,则找到答案
若遍历完所有的出发点都没有找到,则不存在
方法二:跳跃
算法描述
和暴力算法基本一致,只是需要记录在当前尝试中能向前走多少个点,下一次尝试要跳过中间能经过的那些点,以第一个走不到的点作为出发点。
参考代码
方法一:暴力
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
vector<int> Gas, Cost;
Gas.insert(Gas.end(), gas.begin(), gas.end());
Gas.insert(Gas.end(), gas.begin(), gas.end());
Cost.insert(Cost.end(), cost.begin(), cost.end());
Cost.insert(Cost.end(), cost.begin(), cost.end());
for (int i = 0; i < gas.size(); i++) {
bool flag = true;
for (int j = i, g = 0; j < i + gas.size(); j++) {
g += Gas[j] - Cost[j];
if (g < 0) {
flag = false;
break;
}
}
if (flag)
return i;
}
return -1;
}
};
方法二:跳跃
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
vector<int> Gas, Cost;
Gas.insert(Gas.end(), gas.begin(), gas.end());
Gas.insert(Gas.end(), gas.begin(), gas.end());
Cost.insert(Cost.end(), cost.begin(), cost.end());
Cost.insert(Cost.end(), cost.begin(), cost.end());
int i, j, leftGas;
for (i = 0; i < gas.size(); i += j - i + 1) {
bool flag = true;
for (j = i, leftGas = 0; j < i + gas.size(); j++) {
leftGas += Gas[j] - Cost[j];
if (leftGas < 0) {
flag = false;
break;
}
}
if (flag)
return i;
}
return -1;
}
};