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.
本题采用贪心算法,若从i点无法到达k点,那么从i~k的任意一点都无法到达k。同时若gas的总和大于cost的总和,则说明必然有解。
所以核心就是寻找所谓的start,设定tank变量存储当前gas和cost的差,当tank小于0,说明存在上述i~k的情况,便将start跳到tank之后。一轮检索之后,比较总的gas与cost,若大于等于0,则返回cost;小于0则意味着无法转一圈,则返回-1.
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start(0),total(0),tank(0);
for(int i=0;i<gas.size();i++) if((tank=tank+gas[i]-cost[i])<0) {start=i+1;total+=tank;tank=0;}
return (total+tank<0)? -1:start;
}
};
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start(0),total(0),tank(0);
for(int i=0;i<gas.size();i++) if((tank=tank+gas[i]-cost[i])<0) {start=i+1;total+=tank;tank=0;}
return (total+tank<0)? -1:start;
}
};