您的位置:首页 > 其它

Gas Station(leetcode)

2014-11-15 09:14 302 查看
题目:

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.
题目来源:https://oj.leetcode.com/problems/gas-station/

解题思路:从gas[i]>cost[i]的汽油站开始,保证车内加的油要大于消耗的油即可,如果不满足,则从不满足的值k的下一个k+1开始接着寻找这个能满足的i,直到最后。《leetcode题解》中的代码更短,思路也更清晰。

#include<iostream>
#include<vector>
using namespace std;

int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
if(gas.empty())
return 0;
for(int i=0;i<gas.size();i++)
{
if(gas[i]>=cost[i])
{
int j=0,sumGas=0,sumCost=0;
bool flag=true;
for(j=i;j<gas.size();j++)
{
sumGas+=gas[j];
sumCost+=cost[j];
if(sumGas<sumCost)
{
i=j;
flag=false;
break;
}
}
j=gas.size()-1;
if(flag==true)
{
for(j=0;j<i;j++)
{
sumGas+=gas[j];
sumCost+=cost[j];
if(sumGas<sumCost)
return -1;
}
if(i==j)
return i;
}
}
}
return -1;
}

int main()
{
const int N=1;
int A[]={2};
int B[]={2};
vector<int> gas(A,A+N);
vector<int> cost(B,B+N);
int result=canCompleteCircuit(gas,cost);

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