题目:https://oj.leetcode.com/problems/gas-station/
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.
最简单的想法当然是暴力遍历,如果能走到下一个加油站就继续不行就换一个开始结点进行遍历。。。但是想着就算这个算法能够AC也没啥技术含量,没什么意思。所以还是上网看了一下别人的解题报告,果然找到了一个比较巧妙的解法。
这种解法基于一个条件:
如果以加油站i为起点,汽车能够从加油站i到达加油站i+1则gas[i] - cost[i]肯定要大于等于0。如果能够到达第i + 2个加油站,那么gas[i] - cost[i] + gas[i + 1] - cost[i + 1]肯定也要大于等于0.......所以如果从i出发到某节点是出现gas[i] - cost[i] + ...+gas[j] - cost[j] < 0则说明从加油站i不能到达加油站j,并且从j之前的任何加油站出发也不能到达加油站j(可以这样想,如果汽车能够从加油站i到加油站k,k位于i与j之间,那么说明汽车到达k之后油箱里面剩的油至少为0,如果从i不能走到j,则从k也不能走到j),所以可以直接跳过i与j之间的加油站,测试从j+1出发能不能走到最后。
所以可以定义一个数组tmp[i] = gas[i] - cost[i]。用total计算tmp数组的总和。如果total>=0,则表明汽车是能够绕一圈的,否则不能。
另外,还有一个问题困扰到我了,为什么能走到最后一个加油站,就能走一圈呢?(不是很明白==)
AC代码:
<span style="font-size: 14px;">class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int len = gas.size();
//先求数组tmp = gas[i] - cost[i]
vector<int> tmp(len,0);
for(int i = 0;i < len;i++){
tmp[i] = gas[i] - cost[i];
}
//因为如果车能从点i到点j则必须有从i到j的tmp之和大于0
//用sum记录车能否开到结点i+1,如果sum < 0表示不行,则要从i + 1作为下次的开始结点开始走
//total用来记录车能否绕行一圈,如果total > 0表示可以
int sum = 0,total = 0,start = 0;
for(int i = 0;i < len;i++){
sum += tmp[i];
total += tmp[i];
if(sum < 0){
start = i + 1;
sum = 0;
}
}
if(total < 0) return -1;
else return start;
}
};</span>