Gas Station--LeetCode
There are N gas stations along a circular route, where the amount of gas at stationi isgas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from stationi 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.
#include <iostream>
#include <vector>
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int index,cur;
int len = gas.size();
int begin=0,curNum;
for(begin =0;begin<gas.size();begin++)
{
cur =0;
curNum=0;
index = begin;
while(curNum<len)
{
index = index%len;
cur +=cost[index];
if(cur< cost[index])
break;
else
cur -=cont[index];
curNum++;
index++;
}
if(curNum == len)
return begin;
}
return -1;
}
还没有评论,来说两句吧...