南通网站建设方案托管自动app优化官网
134. 加油站 - 力扣(LeetCode)
一开始的思路是循环每一次出发的位置,然后把数组进行拼接,如果能遍历完拼接的数组,则可以达到最开始的位置,但是在最后几个案例会超时,时间复杂度为o(N²)
留一下自己的代码
public static int canCompleteCircuit(int[] gas, int[] cost) {int n = gas.length;int result = -1;for (int i = 0; i < n; i++) {int gasNum = gas[i];int j = i;while (gasNum - cost[j] >= 0) {gasNum = gasNum - cost[j] + gas[(j + 1) % n];j = (j + 1) % n;if(j==i)return i;}}return result;}
public static int canCompleteCircuit(int[] gas, int[] cost) {int n = gas.length;for (int i = 0; i < n; i++) {int rest = gas[i] - cost[i];int index = (i + 1) % n;while (rest > 0 && index != i) {rest += gas[index] - cost[index];index = (index + 1) % n;//System.out.println(rest);}if (rest >= 0 && index == i) return i;System.out.println(i);if (index <= i) return -1;i = index - 1;}return -1;}