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.
原问题链接:https://leetcode.com/problems/gas-station/
?
从问题描述里我们相对比较容易找到一个思路,就是因为这里是走一圈要求遍历整个数组。那么它们所有消耗的汽油以及加的汽油的差值就能确定我们最后能否完整的走一圈。至少通过这个条件我们就可以判断能否走完一圈。
现在剩下的就是要确定怎么找到那个可以走完一圈的点。假设我们从起点0开始,当它往前一直累加的某个点的时候,出现求和的值小于0了。我们该怎么选择呢?从这个累加和小于0的结果我们至少可以知道,只要绕这一圈,从起点到这个点的这一段的总和是小于0的。我们取当前点的后面一个位置才有可能找到累加和大于0的段。在实现的时候,我们取的当前节点的后一个可能超过节点n,那么这个时候需要进行取余操作。在最终我们取到的节点是否有效就取决于所有节点的累加和是否大于等于0。
详细的代码实现如下:
?
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; int curSum = 0, totalSum = 0, start = 0; for(int i = 0; i < n; i++) { curSum += gas[i] - cost[i]; totalSum += gas[i] - cost[i]; if(curSum < 0) { start = (i + 1) % n; curSum = 0; } } return totalSum >= 0 ? start : -1; } }
?
原文:http://shmilyaw-hotmail-com.iteye.com/blog/2309136