0%

LeetCode-134

题目

Snipaste_2020-11-18_13-02-29.png

结果

Snipaste_2020-11-18_13-04-57.png

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for (int i = 0; i < gas.length; i++) {
if (winnable(gas, cost, i)) {
return i;
}
}
return -1;
}

private boolean winnable(int[] gas, int[] cost, int startPos) {
int index = startPos;
int gasLeft = 0;
do {
gasLeft += gas[index];
if (gasLeft >= cost[index]) {
gasLeft -= cost[index];
index++;
if (index >= gas.length) {
index -= gas.length;
}
} else {
return false;
}
} while (index != startPos);
return true;
}
}

复杂度

时间复杂度:O(n²)

空间复杂度:O(1)