您的位置:首页 > 其它

LeetCode Gas Station

2015-02-14 18:43 302 查看


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.

这道题也挺麻烦的。乍看不难,用最简单的算法就是一个一个点地计算,计算到没油了,证明这点不能作为出发点。移动到下一个点作为出发点。这样的话思路还是挺简单的,不过这样写不accepted的,因为编译超时。

我觉得做这道题的关键是要可以总结出来这道题目的属性,注意Note这个地方,其属性主要有两个:

1 如果总的gas - cost小于零的话,那么没有解返回-1

2 如果前面所有的gas - cost加起来小于零,那么前面所有的点都不能作为出发点。

ps:显然 如果前面所有的gas - cost加起来小于0 则该点必然不能作为起点 假设该点的前一个点可通过 若当前点sum小于0则说明加上前一个点多给的油都不能通过,那么他本身就不能作为起点.

主要利用属性2可以写两个程序:

程序一:记录最后一个加起来小于零的索引,然后返回这个索引+1就是答案了。

程序二:跳跃式,跃过不能作为出发点的点,加速循环

不总结出这些特性是难做出来的。

程序一:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int sum = 0;
int total = 0;
int j = -1;
for(int i = 0; i < gas.size() ; ++i)
{
sum += gas[i]-cost[i];
total += gas[i]-cost[i];
if(sum < 0)
{
j=i; sum = 0;
}
}
if(total<0) return -1;
else return j+1;
}
};


程序二:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int n = gas.size();
int j = 0;
for(int i=0; i<n;)
{
j=i;
if(startPoint(gas, cost, j))
return i;
i += j;
}
return -1;
}

bool startPoint(vector<int> &gas, vector<int> &cost, int& start)
{
int n = gas.size();
int left = 0;
int temp;
for(int i=start; i<(n+start); i++)
{
temp = i%n;
left += gas[temp]-cost[temp];
if(left<0)
{
start = i-start+1;
return false;
}
}
return true;
}
};


第一种代码简单,却比较难想出来,第二种还比较好想出来吧。

我想想到底如何对付这些题目呢?尤其如果面试的时候,时间又受限,那更高难度了。

我想到的策略就是:先举些列子,观察他们的特性,然后总结出来,再设计算法吧。谁没做过,能一下子就看出其中的规律吗?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: