leetcode 刷题之路 68 Gas Station

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.

一种做法是以每个站为起点判断是否能够在行走一个周期后回到自身。

AC code:

class Solution {
 public:
	 int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
	 {
		 int res = 0, i = res, n = gas.size(), left = 0;
		 while (res<n)
		 {
			 left = left + gas[i] - cost[i];
			 if (left<0)
			 {
				 res++;
				 left = 0;
				 i = res;
			 }
			 else
			 {
				 i = (++i) % n;
				 if (i == res)
					 return res;
			 }

		 }
		 return -1;
	 }
 };
其实还有更优化的方法,在判断以当前站点res为起始站点是否能够回到当前站点的过程中,如果在站点i出现不能到达i+1站点的情况,那么以从当前站点res到A直接的所有站点为起始点,都不能跨越过i~i+1这个坎。可以这样理解这句话,对于res~i之间的任意站点x,汽车从res出发到达x剩余的油量大于等于0,所以汽车从res出发到达i剩余的油量大于等于从站点x出发到达i剩余的油量。
基于上面的结论,可以知道,下一个可能的起始点就是i+1,我们直接让res等于i+1,再继续执行程序,直到res等于n,此时说明不存在满足条件的站点。
优化后的方法时间复杂度O(n)。

AC code:

class Solution {
 public:
	 int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
	 {
		 int res = 0, i = res, n = gas.size(), left = 0;
		 while (res<n)
		 {
			 left = left + gas[i] - cost[i];
			 if (left<0)
			 {
				 if(i>res)
				    res=i;
				else 
				    res++;
				 left = 0;
				 i = res;
			 }
			 else
			 {
				 i = (++i) % n;
				 if (i == res)
					 return res;
			 }

		 }
		 return -1;
	 }
 };





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值