# Gas Station

153人阅读 评论(0)

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.

int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int lenG = gas.size();
int lenC = cost.size();
if(lenG == 0 || lenC == 0 || (lenG != lenC))
{
return -1;
}

int sum = 0;
vector<int> diff;
int tmp = 0;
for(int i = 0; i < lenG; ++i)
{
tmp = gas[i] - cost[i];
diff.push_back(tmp);
sum += tmp;
}

if(sum < 0)
return -1;
int index = 0;
for(int i = 0; i < lenG; ++i)
{
int tmpSum = diff[i];
if(tmpSum < 0)
continue;
int flag = 1;
for(int j = i + 1; j < lenG; ++j)
{
tmpSum += diff[j];
if(tmpSum < 0)
{
flag = 0;
i = j;
break;
}
}

if(flag)
{
index = i;
break;
}
}

return index;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：8125次
• 积分：479
• 等级：
• 排名：千里之外
• 原创：42篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
评论排行