此题思路较为简单,即判断是否存在从某一点开始,在保证每经过一个加油站都加上所有油的前提下,汽车都保持行驶状态,直至行驶完一圈。
需要注意的是程序结束条件。
代码
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = 0;
int j = start;
int gasAll = gas[j];
int size = gas.size();
int count = 0;
while(true)
{
if(count==size)
return start;
else
{
if(gasAll>=cost[j])
{
gasAll -= cost[j];
j = (j+1)%size;
gasAll += gas[j];
count++;
}
else
{
start = (start+1)%size;
if(start==0)
return -1;
j = start;
gasAll = gas[j];
count = 0;
}
}
}
}
};