题目原型:
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.
基本思路:
遍历一圈,如果说剩下的油和待加的油能够走过这一站的话则继续,否则改变起点继续,当起点回到原来走过的点时表示不能
public int canCompleteCircuit(int[] gas, int[] cost)
{
if(gas.length==0||gas==null)
return -1;
if(cost.length==0||cost==null)
return 0;
int index = 0;
int rest = 0;//还剩多少油
int count = 0;//走过的长度
int startIndex = 0;//起始点
int len = gas.length;
boolean isCircle = false;//记录是否回到了曾经走过的点
while(count<len)
{
if(rest<0||rest+gas[index]<cost[index])
{
startIndex = (index+1)%len;
//起点回到曾经走过的点那么就说明不能通过
if(isCircle)
return -1;
count = 0;
}
else
{
rest = rest + gas[index] - cost[index];
count++;
}
if(index+1>=len)
isCircle=true;
index = (index+1)%len;
}
return startIndex;
}
原文:http://blog.csdn.net/cow__sky/article/details/21867679