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.
做这道题的时候有点闹心,一直感觉状态不对。刚看完题目觉得题目没什么意思,就有了一个简单的n*n的思路,简单写了代码提交结果超时。想想肯定是要O(n)的复杂度解法,于是想了一个简单的贪心算法:从头开始走,如果碰到失败的情况,就从失败的下一个station开始,最多走2*gas.size()的长度是考虑到可能最后一个gas有充足的油量。
O(n*n)实现(不知道对不对,因为没有AC):
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.
做这道题的时候有点闹心,一直感觉状态不对。刚看完题目觉得题目没什么意思,就有了一个简单的n*n的思路,简单写了代码提交结果超时。想想肯定是要O(n)的复杂度解法,于是想了一个简单的贪心算法:从头开始走,如果碰到失败的情况,就从失败的下一个station开始,最多走2*gas.size()的长度是考虑到可能最后一个gas有充足的油量。
最开始没有end变量,结果总是找不对成功跳出的条件,加完一个变量后,发现太简单了。所以以后如果碰到不好判断的情况,不妨加一个变量试试,这样可以多记录一个状态,可能会让情况比较明朗。
O(n)实现:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int len = gas.size();
int start = 0;
int end = len-1;
int tank = 0;
for (int i = 0; i < 2*len; i++)
{
tank += gas[i%len] - cost[i%len];
if (tank < 0)
{
start = i+1;
end = i;
tank = 0;
}
else if (i%len == end)
return start;
}
return -1;
}
O(n*n)实现(不知道对不对,因为没有AC):
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int index = -1;
for (int i = 0; i < gas.size(); i++)
{
int tank = 0;
for (int j = 0; j < gas.size(); j++)
{
int station = (i+j)%gas.size();
tank += gas[station] - cost[station];
if (tank < 0)
break;
}
if (tank >= 0)
{
index = i;
break;
}
}
return index+1;
}