赞
踩
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)
{
for (int i = 0; i < gas.Length; i++)
{
if (CanCompleteCircuit(gas, cost, i))//汽车从I节点出发,尝试是否可以跑通
{
return i;
}
}
return -1;
}
public bool CanCompleteCircuit(int[] gas, int[] cost, int start)
{
int now = gas[start];
int count = 0;
while (count < gas.Length)
{
now -= cost[start];//减油
if (now < 0) return false;//汽油不能到达下一个节点
count++;
start++;
if (start >= gas.Length)
start = 0;
now += gas[start];//加油
}
return true;//全部的节点已经跑通,回到原节点
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。