题目描述:
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.
使用贪心的思想,首先遍历gas station,找到第一个满足条件:gas[i]>=cost[i]的gas station,
gas[i]>=cost[i]说明从当前gas station可以到达下一个gas station,
然后从该gas station i 开始,计算能否走一圈。如果可以编号i即为所求;
否则找到gas station i后面的第一个满足条件:gas[j]<cost[j]的gas station,然后找到
gas station j后面的第一个满足条件:gas[k]>=cost[k]的gas station即为下一个可以计算能否走一圈的开始位置。
这样做的目的是跳过连续的满足条件:gas[i]>=cost[i]的gas station,因为如果从满足这个条件的gas station的第一个
位置处开始都不能走一圈,那么从满足这个条件的后面连续的任何一个开始都不可能走一圈。
AC代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
if (n == 0) return 0;
for (int i = 0; i < n;){
if (gas[i] >= cost[i]){
int pre = gas[i] - cost[i];
int j = i + 1;
for (; j < n; ++j){ //找到gas station i后面的第一个满足条件:gas[j]<cost[j]的gas station
if (gas[j] < cost[j])
break;
}
for (int k = i + 1; k < n; ++k){//从gas station i 开始,计算能否走一圈
pre = pre + gas[k] - cost[k];
if (pre < 0){
break;
}
}
if (pre < 0){ //如果从gas station i 开始不能走一圈,跳过i后面连续的满足条件:gas[i]>=cost[i]的gas station
i = j + 1;
continue;
}
for (int k = 0; k < i; ++k){//如果从gas station i 开始不能走一圈,跳过i后面连续的满足条件:gas[i]>=cost[i]的gas station
pre = pre + gas[k] - cost[k];
if (pre < 0) break;
}
if (pre < 0){
i = j + 1;
continue;
}
else return i;
}
else{
++i;
}
}
return -1;
}
};