首页 > 代码库 > leetcode 刷题之路 68 Gas Station

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