题目描述
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.
解题思路
这题的意思是求出从哪一个油站开始,能够走完整个里程,并且这个结果唯一。
首先,我们可以得到所有油站的油量totalGas,以及总里程 消耗的油量totalCost ,如果totalCost>totalGas ,肯定不能走完真个路程。
如果 totalGas >totalCost ,假设现在我们到达了第i个油站, 这时候 还 剩余的油量 为sum,如果 sum + gas[i] - cost[i] < 0 ,我们则无法到达下一站,所以起点一定不再第i个油站以及之前的位置, 因为在第i位置燃料已经不够了,无法继续。所以起点就在i位置以后的某个位置。
程序实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum=0; int total=0; int k=0; for(int i=0;i<gas.length;i++){ sum+=gas[i]-cost[i]; if(sum<0){ sum=0; k=i+1; } total+=gas[i]-cost[i]; } return total<0? -1:k; } }
最后
以上就是自由心情最近收集整理的关于算法系列——加油站(Gas Station)的全部内容,更多相关算法系列——加油站(Gas内容请搜索靠谱客的其他文章。
发表评论 取消回复