您的位置:首页 > 其它

LeetCode 之 Gas Station

2013-11-21 23:28 316 查看
原题:

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.
此题为了减少时间,肯定不能用暴力解决的方法,学渣综合了网上好多人的方法,先将学渣的思路说一下:
1假设从0点开始走,设两个index,一个为start,一个为current,start代表此次是从start开始走,current代表从start开始走到了current,如图1

2 设一个int叫做myGas,代表当前我的车所剩的油量,开始为0

3 车当前走在i点,判断能否向前走,此时需要判断myGas+gas[current]-cost[current]是否为非负数,如果可以向前走,立刻走一步,然后把油量更新,然后判断start和current是否相等,如果相等,说明这个点可以走一圈,返回这个坐标;如果不能往前走,说明当前设的起始点不行,需要回退一个考虑

4 在起始点回退时,由于起始点也会有油量的消耗和库存,把结余的油量加在当前的油箱里,判断是否能够前行

5如果start==current,说明已经走了一圈,都不行,此时返回-1

综合如图2



图1



图2

代码(44ms):

class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.

int start = 0;

int current = 0;

int myGas = 0;

do{
//可以继续前进
if(myGas + gas[current] >= cost[current] ){
//车上的油更新
myGas=myGas + gas[current] - cost[current];
current=(current+1)%gas.size();
if(current == start){
//回到了原点,说明能够循环
return current;
}
}

else{
//如果不能前进,起始点向前走一位,而且要把起始点的油加在车里,负数也要加上去
start= (start+gas.size()-1)%gas.size();
myGas = myGas + gas[start] - cost[start];
}

//一圈都不能循环,中断循环
}while(start!=current);
return -1;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: