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.
//方法一:O( N) 的解法是,设置两个变量,sum表示起点为station时当前的总油量;total则为全程的总油量,如果total不小于0,则返回通过sum得到起点的下标station;如果total小于0,则返回 -1。
//时间复杂度 O(n) ,空间复杂度 O(1)
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int total = 0;
int station = 0;
for(int i = 0, sum = 0; i < gas.size(); i++)
{
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if(sum < 0)
{
station = i + 1; //起点位置
sum = 0;
}
}
return total < 0 ? -1 : station;
}
};//方法:超时, O (N^2) 的解法,对每个点进行模拟
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int sum = 0;
for(int i = 0; i < gas.size(); i++)
{
sum = 0;
for(int j = i; j < gas.size(); j++)
{
sum += gas[j] - cost[j];
if(sum < 0)
break;
}
if(sum < 0)
continue;
for(int j = 0; j < i; j++)
{
sum += gas[j] - cost[j];
if(sum < 0)
break;
}
return i;
}
return -1;
}
};
原文地址:http://blog.csdn.net/keyyuanxin/article/details/46591715