题目描述:
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 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.
Notice
The solution is guaranteed to be unique.
Given 4
gas stations with gas[i]=[1,1,3,1]
, and thecost[i]=[2,2,1,1]
. The starting gas station's index is 2
.
O(n) time and O(1) extra space
这题用greedy算法,感觉不是那么正统的题。这题code中用了两个变量:local diff和global diff。local diff一直计算到i所费油量的总和,如果它<0,那么表示从前的那些gas stations都不是我们要找的,于是要把local diff和index reset,继续找后面的candidates。global diff为所有花费的油量总和,如果它<0,那么表示没有答案,return -1.
Mycode(AC = 37ms):
class Solution {
public:
/**
* @param gas: a vector of integers
* @param cost: a vector of integers
* @return: an integer
*/
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// write your code here
if (gas.size() == 0 || cost.size() == 0) {
return -1;
}
int local_sumdiff = 0, global_sumdiff = 0;
int idx = -1;
for (int i = 0; i < gas.size(); i++) {
local_sumdiff += gas[i] - cost[i];
global_sumdiff += gas[i] - cost[i];
// if local_sumdiff < 0, it means all the
// previous gas stations are not candidates,
// then reset the local_sumdiff and idx to
// seek latter ones
if (local_sumdiff < 0) {
local_sumdiff = 0;
idx = i;
}
}
if (global_sumdiff < 0) {
return -1;
}
else {
return (idx + 1) % gas.size();
}
}
};