标签:style color os io art ar 时间 line
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剩余的油量。
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; } };
leetcode 刷题之路 68 Gas Station,布布扣,bubuko.com
标签:style color os io art ar 时间 line
原文地址:http://blog.csdn.net/u013140542/article/details/38469135