本文共 1359 字,大约阅读时间需要 4 分钟。
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.public int canCompleteCircuit(int[] gas, int[] cost)
这题其实是贪心法,只需要转一圈即可。从任意点开始即可,只要没有走过“第一个”起始点,当前有油就延续当前路径,不够油就相当于从当前点为新一个起始点出发。只要找到一个起始点能够走完一圈就好。但如果过了第一个起始点还是遇到不够油继续的情况就可以中断了,这表示没有一个起始点是可以走完一圈的。
这个算法是缘于下面这一个原则:如果我们有ABCDEFG....N个点。
如果以A为起点,A-》B-》C-》D 这个路径没有办法走下去,那么A和B和C都不可能做起点。所以当走过第一个起始点还是找不到可行的点,实际上就已经排除了所有可能的起始点了。
给出代码如下:
public int canCompleteCircuit(int[] gas, int[] cost) { int cur_gas = 0; int cur_station = 0; int res = 0; while(cur_gas >= 0 || cur_station < gas.length){ res = cur_gas >= 0 ? res : cur_station; cur_gas = cur_gas >= 0 ? cur_gas : 0; cur_gas += gas[cur_station % gas.length]; cur_gas -= cost[cur_station % gas.length]; if(cur_gas >= 0){ if((cur_station + 1) % gas.length == res) break; } cur_station++; } return cur_gas >= 0 ? res : -1; }
转载地址:http://rgaxb.baihongyu.com/