//起点的可能位置列表 List<Integer> list = new ArrayList<>(); int sum = 0; for (int i = 0; i < gas.length; i++) { last[i] = gas[i] - cost[i]; sum+=last[i]; if(last[i]>0){ list.add(i); } } //不可能跑一圈 if(sum<0){ return -1; } int res = -1; //遍历所有的可能节点 for (Integer i : list) { boolean[] flag = newboolean[gas.length]; flag[i] = true; int curr = i; int j=0; sum = last[curr]; //跑圈 for(j=0;j<gas.length;j++){ int next = curr+1==gas.length?0:curr+1; sum +=last[next]; //油不够了 if(sum < 0){ break; } curr = curr+1==gas.length?0:curr+1; } //可以跑一圈 if(j==gas.length){ return i; }
} return res;
} }
精简代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ publicintcanCompleteCircuit(int[] gas, int[] cost){ int start = 0, sum = 0, tank = 0; for (int i = 0; i < gas.length; i++) { tank += gas[i] - cost[i]; if (tank < 0) { start = i + 1; sum += tank; tank = 0; } } return sum + tank >= 0 ? start : -1;