【gas-station】

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.

Note: 

The solution is guaranteed to be unique.

题意:
环形路线上有N个加油站,每个加油站有汽油gas[i],从每个加油站到下一站消耗汽油cost[i]
问从哪个加油站出发能够回到起始点,如果都不能则返回-1;注意,解释唯一的;

思路:
累加在每个位置的left += gas[i]-cost[i].就是在每个位置剩余的油量,如果left一直大于0,
则可一直走下去,如果left小于0,那么就从下一个位置重新开始计数,并且将之前欠下的多少记录下来,
如果最终遍历完数组剩下的燃料足以弥补之前不够的,那么就可以到达,并返回最后一次开始的位置,否则返回-1;


论证这种方法的正确性:
1,如果从头开始,每次累计剩下的油量都为整数,那么没有问题,它可以从头开到结束
2. 如果到中间的某个位置,剩余的油量为负了,那么说明之前积累下来的油量不够从这一战
到下一站,那么就从下一站从新开始计数,为什么从下一站,而不是从之前的谋战呢?
因为第一站剩余的油量肯定大于等于0的,然而到当前油量变负了,说明从第一站之后开始的话当前油量只会更少
不会怎加,也就说从第一站之后,当前站之前的某站出发到当前站之前的某站出发到当前站出发的剩余
的油量是不大可能大于0的,所以只能从下一站重新出发开始计算从下一站开始剩余的油量
并且把之前欠下的油量也累加起来,看到最后剩余的油量是不是大于欠下的油量。

class Solution
{
public:
	int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
	{
		int start = 0;
		int lack = 0;
		int left = 0;

		for (int i=0; i<gas.size(); i++)
		{
			left += gas[i]-cost[i];
			if (left<0)
			{
				start = i + 1;
				lack += left;
				left = 0;
			}
		}

		return left + lack >= 0 ? start : -1;
	}
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值