134. 加油站

自己做(超时)

java
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int res = -1;
for(int i = 0; i < gas.length; i++){
int sum = 0;
//顺时针走
for(int j = 0; j < gas.length; j++){
int index = (i + j) % gas.length;
sum += gas[index] - cost[index];
if(sum < 0){ //走不到
sum = 0;
break;
}
if(j == gas.length - 1) //走通了
res = i;
}
if(res != -1) //如果已经走通就没必要再走了
break;
}
return res;
}
}
看题解
官方题解

java
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int i = 0;
while (i < n) {
int sumOfGas = 0, sumOfCost = 0;
int cnt = 0;
while (cnt < n) {
int j = (i + cnt) % n;
sumOfGas += gas[j];
sumOfCost += cost[j];
if (sumOfCost > sumOfGas) {
break;
}
cnt++;
}
if (cnt == n) {
return i;
} else {
i = i + cnt + 1;
}
}
return -1;
}
}