大致思路:
题意大概就是:一个环上N个站点,每个站点可以加油gas[i],每个站点到其下一个站点要消耗cost[i],问你能否找到一个起点能够走过环上所有点(终点==起点)
思路就是,可以理解到达每个站点其实要增加gas[i]-cost[i],当然这个数有可能是负数,但是一定要保证总油数sum>=0. 设一个start指针和一个end指针,如果加上之后sum>=0,则end++,否则就start--(因为start++只会让总油更少,只有回退start看看能不能在上一站得到正数的gas[i]-cost[i]增加总油)。直到start==sum,再判断sum最后是否>=0即有无解。
我感觉我学到的就是,这种有起点有终点而且不确定起点终点的问题,可以设两个指针,对不同情况设计指针的不同操作。(之前尺取法就是这个思路)
AC代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size()-1;
int end = 0;
int sum = gas[start] - cost[start];
while(start>end)
{
if(sum>=0)
{
sum += gas[end] - cost[end];
end++;
}
else
{
start--;
sum += gas[start] - cost[start];
}
}
if(sum>=0)
return start;
else
return -1;
}
};