一、原题
There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[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.
二、中文
一个环形的跑道上分布着一些加油站,然后一个跑车在这个跑到上奔跑,每个加油站含有的油量使用数组表示,另外一个数组表示的是消费的油量
问一下这个车从某个点开始能否回到原点。
三、举例
自己想象一下吧
四、思路
从每个加油站开始,进行遍历,然后看一下能否回到起点,效率不是很高但是思路还是很简单的,也是贪心算法的一种吧
五、程序
import java.util.*;
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for(int i = 0; i < gas.length; i++){
//从每个车站开始
int j = i;
int tempGas = gas[j];
//如果油量足够到达下一站
while(tempGas >= cost[j]){
tempGas = tempGas - cost[j];
//从这个站接着开始
j = (j + 1) % gas.length;
//如果返回到了起点
if(j == i){
return i;
}
//继续加上这个加油站的油
tempGas = tempGas + gas[j];
}
}
return -1;
}
}