此题思路较为简单,即判断是否存在从某一点开始,在保证每经过一个加油站都加上所有油的前提下,汽车都保持行驶状态,直至行驶完一圈。
需要注意的是程序结束条件。
代码
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;
}
}
}
}
};
本文介绍了一个简单的算法,用于解决汽车能否在加满油的情况下完成一圈行驶的问题。通过判断是否存在一个起点,使得汽车从该点出发并沿环路行驶时始终有足够的油继续前进,最终返回该起点。若无法找到这样的起点,则返回-1。
995

被折叠的 条评论
为什么被折叠?



