本文共 522 字,大约阅读时间需要 1 分钟。
思路:每个加油站提供的油减去下一段路上耗费的油,生成新的数组。循环数组长度2倍的量,找出其中一段长度为数组长且每部的剩余油量都不小于0的;
public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int[] n = new int[gas.length]; for (int i = 0; i < n.length; i++) { n[i] = gas[i] - cost[i]; } int sum = 0; int begin = 0; int truebegin=0; for (int i = 0; i < n.length*2; i++) { sum += n[i%n.length]; while (sum < 0) { sum -= n[truebegin]; begin++; truebegin=begin%n.length; } if (i-begin>=n.length) { return truebegin; } } return -1; }}
转载地址:http://sushb.baihongyu.com/