本题题目要求如下:
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.
就用这张图片来说明吧。。我的算法是寻找最低点。。也就是4,只有从4出发,才有可能避免出现负数点。。。
当然我上面画的是连续图,如果是用离散的话,会有一点小的出入,但总体是这个意思。。
代码如下:
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int concave_x = 0;
int concave_y = 0;
int remain = 0;
int sz = gas.size();
for(int i = 0; i < sz; ++i) {
remain = remain + gas[i] - cost[i];
concave_y = min(remain, concave_y);
if (remain == concave_y)
concave_x = i;
}
if (remain < 0)
return -1;
else
return ((concave_x + 1) % sz);
}
};