2019年1月20日星期日

[LeetCode] 134. Gas Station

O(n^2) 的复杂度好像有些高,不知道有没有更快的方法解决 \(▔▽▔)/

class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
for (int i = 0; i < gas.length; i++) {
int gasInCar = gas[i];
for (int traveled = 1; traveled <= gas.length; traveled++) { // Attn: Made mistake here. traveled should be range from 1 to gas.length (rather than 1 to gas.length - 1)
int j = (i + traveled) % gas.length;
int currentCost = j == 0 ? cost[cost.length - 1] : cost[j - 1];
gasInCar = gasInCar - currentCost;
if (gasInCar < 0) {
break;
}
gasInCar = gasInCar + gas[j];
}
if (gasInCar >= 0) {
return i;
}
}
return -1;
}
}
更新:找到了很巧妙的方法。确实一次遍历就可以解决。~( ̄▽ ̄~)(~ ̄▽ ̄)~
https://blog.csdn.net/JackZhang_123/article/details/78008439

没有评论:

发表评论