题目描述
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.
算法分析
一道很简洁感觉很可爱的小题目www
不知道该归为什么算法,解法很巧妙,时间复杂度O(n),以及O(1)的额外空间。
其实只要gas的和大于cost的和,就一定能找到一个起点了,所以主要需要解决的是如何找到这个起点。
由于路径是个环,为了方便编写代码,首先将起点设到数组的最后一个位置,结尾则是起点的下一个位置(数组的第一个位置,因为是环)。用sum累计从start到end前一位置的剩余油量,之后每次循环若sum<0则将start前移,sum>=0则end后移。start和end重合时退出循环,若能够完成旅行start所在位置则为起点。
具体实现
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];
}
}
if (sum >= 0) return start;
else return -1;
}
};
提交结果
16 / 16 test cases passed.
Status: Accepted
Runtime: 6 ms
Submitted: 29 minutes ago
Your runtime beats 17.78 % of cpp submissions.