题目描述
环形路上有n个加油站,第i个加油站的汽油量是gas[i].
你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。
求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。
注意:
答案保证唯一。
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.
思路:
- 看到题目有点错愕,感觉挺简单,不就是每个加油站都试一试,如果成功就返回嘛!想考什么呢?
- 说做就做,已知第i个加油站的汽油为gas[i],到下一个加油站的耗油量为cost[i],则这一个加油站的“净油量”为gas[i]-cost[i];
- 每一个加油站都试一试,直到找到可以走一圈的加油站。思路太简单了,直接看代码吧。
代码:
class Solution {
public:
int next(int index, int n) // 返回下一个加油站,如果当前是n-1则返回0
{
if (index == n-1)
return 0;
return index + 1;
}
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int n = gas.size();
for (int i=0; i<n; i++)
{
int index = i;
int curgas = gas[i] - cost[i]; // 当前油量
while (curgas >= 0 && next(index, n) != i) // 当油量不为负且没有走一圈时
{
index = next(index, n);
curgas += (gas[index] - cost[index]); // 到下一个加油站
}
if (curgas >= 0) // 如果成功走完一圈
return i; // 找到结果,返回
}
return -1; // 没有能走一圈的起点
}
};
写完之后索然无味,感觉肯定有什么更好的办法,想到大佬们从来不会让我失望,就赶快去瞅了一眼,果然!!!!
大佬们的代码:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size()-1;
int end = 0;
int sum = gas[start] - cost[start];
while (start > end)
{
if (sum >= 0)
{
sum += gas[end] - cost[end];
end++;
}
else
{
start--;
sum += gas[start] - cost[start];
}
}
return sum >= 0 ? start : -1;
}
};
思路:
- 从start出发, 如果油量足够, 可以一直向后走 end++; 油量不够的时候,start向后退 最终 start ==
end的时候,如果有解一定是当前 start所在位置。
学习了!!