leetcode-Gas Station

来源:互联网 发布:齿轮参数计算软件 编辑:程序博客网 时间:2024/06/10 21:34

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.

思路:首先比较gas数组的和与cost数组的和,如果gas数组的和较小,说明不能够走一圈,否则进一步计算开始的index。

      开始的index的特点:从index之后,gas[i]-cost[i]的和要么递增,要么大于等于0.(要点在于注意到其特点)

      用变量sum存储其和,如果和sum递增或者大于等于0,并且开始index==-1,则更新index=i;否则,更新index=-1;

代码:

int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int totalGas=0;
int totalCost=0;
int sizeOfGas=gas.size();
int sizeOfCost=sizeOfGas;
for(int i=0; i<sizeOfGas; ++i)
{
totalGas+=gas[i];
}
for(int i=0; i<sizeOfCost; ++i)
{
totalCost+=cost[i];
}
if(totalGas < totalCost)
{
return -1;
}
else
{
int sum=gas[0]-cost[0];
int indexOfStart=sum>=0?0:-1;
for(int i=1; i<sizeOfGas; ++i)
{
if((sum+gas[i]-cost[i])>=0 || (sum+gas[i]-cost[i])>=sum)
{
sum+=gas[i]-cost[i];
if(indexOfStart == -1)
{
indexOfStart=i;
}
}
else
{
sum+=gas[i]-cost[i];
indexOfStart=-1;
}
}
return indexOfStart;
}

}

另一个较好理解的思路:

记录最后一个gas[i]-cost[i]加起来小于零的索引,然后返回这个索引+1就是答案了。

int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int sum = 0;
int total = 0;
int j = -1;
for(int i = 0; i < gas.size() ; ++i)
{
sum += gas[i]-cost[i];
total += gas[i]-cost[i];
if(sum < 0)
{
j=i; sum = 0;
}
}
if(total<0) return -1;
else return j+1;
}

0 0
原创粉丝点击