题目描述
There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[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.
分析
> 首先这道题需要解决两个问题1,能否绕一圈;2,如果能,起点在哪?
>定义数组arr,arr[i]=gas[i]-cost[i] (0<=i <n)
>第一个问题很好解决,遍历数组arr求和,大于0则说明能够转一圈,O(N)的时间复杂度
>第二个问题,假设sum[i,j]= ∑diff[k] ,如果sum[i,j]<0,说明i肯定不是起点,假设s为[0,n]的解,可以推断sum[k,s-1](0=<k<=s-1)肯定是小于0的(否则解就为k),同理,sum[s,n]一定是大于0的,否则解就不是s,而是k和n之间的一个点,那么问题就可以转化为,在s和n之间找到第一个以n为终点的子序列,子序列和必须大于0
>结合起来,这两个问题就可以在一个循环内解决了
代码如下:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
vector<int> arr;
for(int i=0;i<gas.size();i++)
{
arr.push_back(gas[i]-cost[i]);
}
int totle=0;
int sum=0;
int index=0;
for(int i=0;i<gas.size();++i)
{
sum+=arr[i];
totle+=arr[i];
if(sum<0)
{
sum=0;
index=i+1;
}
}
return totle>=0?index:-1;
}