您的位置:首页 > 其它

leetcode-gas station

2014-06-06 10:57 411 查看


Gas Station

Total Accepted: 12395 Total
Submissions: 50855My Submissions

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.

Have you been asked this question in an interview?

最开始的方法,超时了:

class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int len = gas.size();
int tank ;
int start,i;
for(start=0;start<len;start++)
{
tank = 0;
for(i=0;i<len;i++)
{
if(i+start<len)
{
tank += gas[i+start];
tank -= cost[i+start];
if(tank<0)break;
}
else
{
tank += gas[i+start-len];
tank -= cost[i+start-len];
if(tank<0)break;
}

}
if(i!=len)continue;
else
break;
}
if(start==len)return -1;
return start;
}
};


int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// Note: The Solution object is instantiated only once.
int total = 0;
int currentgas = 0;
int startpoint = -1;
int sz = gas.size();
for(int i = 0; i < sz; i++)
{
currentgas += gas[i] - cost[i];
total += gas[i] - cost[i];
if(currentgas < 0)
{
startpoint = i;
currentgas = 0;
}
}
return total >= 0 ? startpoint+1 : -1;
}


解题报告:

当然,这题如是一个一个开始,然后把所有点走一遍,再判断是否成立,这个是可以的,也是最正常的思维,但复杂度O(n2)

这就是第一种解法

不得不优化。

有如下规律,如果一串数字,总和大于等于0,则必存在某一点,从这点开始,一真累加,每次都是非负数

这样,我们只需要判断最后的结果是否为非负就知道是否存在解,即total>=0

要找到开始的那个点,就判断是否是一直>=0,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: