leetcode-Gas Station

本文探讨了一个在给定油站路线中寻找起始油站的问题,该油站能够使车辆完成循环旅行。通过比较总汽油量与总成本,文章提出了一个算法来确定起始油站的索引,确保车辆能够成功完成旅程。算法考虑了汽油与成本的差异,以优化起始点选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值