【题目】
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.
【题意】
在一个圆形路径上有N个加油站,在位置 i 上的汽油的数目为gas[i]
.
你有一个汽车,这个汽车的油箱是无限容量的,它从加油站 i 到 加油站 (i+1)需要耗费的汽油数为cost[i]. 开始这段旅程的时候,你的起始状态是在加油站中的一个,油箱为空的.若一次性完成整个的圆形路途,返回你的其实加油站的序号,若不能完成整个路途,返回-1.
注意:解决方案保证是唯一的.
【算法分析】
1. 暴力破解
暴力解法比较好想,但是超时了。就是从每一个站开始,一直走一圈,累加过程中的净余的油量,看它是不是有出现负的,如果有则失败,从下一个站开始重新再走一圈;如果没有负的出现,则这个站可以作为起始点,成功。可以看出每次需要扫描一圈,对每个站都要做一次扫描,所以时间复杂度是O(n2)
public static int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int i = 0;
int j = 0;
int left = 0;
int res = -1;
for(int k = 0; k < len; k++){
left = 0;
while(i < len){
left += gas[i] - cost[i];
if(i+ 1 >= len){
i = (i+1)%len;
}
if(left < 0){
break;
}
}
}
return res;
}
2. 思路: 累加在每个位置的left += gas[i] - cost[i], 就是在每个位置剩余的油量, 如果left一直大于0, 就可以一直走下取. 如果left小于0了, 那么就从下一个位置重新开始计数, 并且将之前欠下的多少记录下来, 如果最终遍历完数组剩下的燃料足以弥补之前不够的, 那么就可以到达, 并返回最后一次开始的位置.否则就返回-1.
证明这种方法的正确性:
1. 如果从头开始, 每次累计剩下的油量都为整数, 那么没有问题, 他可以从头开到结束.
2. 如果到中间的某个位置, 剩余的油量为负了, 那么说明之前累积剩下的油量不够从这一站到下一站了. 那么就从下一站从新开始计数. 为什么是下一站, 而不是之前的某站呢? 因为第一站剩余的油量肯定是大于等于0的, 然而到当前一站油量变负了, 说明从第一站之后开始的话到当前油量只会更少而不会增加. 也就是说从第一站之后, 当前站之前的某站出发到当前站剩余的油量是不可能大于0的. 所以只能从下一站重新出发开始计算从下一站开始剩余的油量, 并且把之前欠下的油量也累加起来, 看到最后剩余的油量是不是大于欠下的油量.
public static int canCompleteCircuit(int[] gas, int[] cost) {
int len = gas.length;
int left = 0;
int lack = 0;
int s = 0;
for(int i = 0; i < len; i++){
left += gas[i] - cost[i];
if(left < 0){
lack += left;
s = i + 1;
left = 0;
}
}
return left + lack >= 0 ? s : -1;
}