# Leetcode - Gas Station

My code:

``````public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0)
return -1;
int len = gas.length;
int sum = 0;
int total = 0;
int ret = 0;
int[] diff = new int[len];
for (int i = 0; i < len; i++)
diff[i] = gas[i] - cost[i];
for (int i = 0; i < len; i++) {
total += diff[i];
if (sum < 0) {
sum = diff[i];
ret = i;
}
else {
sum += diff[i];
}
}
if (total < 0)
return -1;
else
return ret;
}

/*
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0)
return -1;
for (int i = 0; i < gas.length; i++) {
if (simulate(i, gas, cost))
return i;
}
return -1;
}

private boolean simulate(int begin, int[] gas, int[] cost) {
int tank = gas[begin];
for (int i = 0; i< gas.length; i++) {
int cos = cost[(begin + i) % gas.length];
if (cos > tank)
return false;
else
tank = tank - cos + gas[(begin + i + 1) % gas.length];
}
return true;
}
*/

}
``````

A -> B ok
A -> B -> C no

B 也到不了C。具体证明看博客。

http://www.programcreek.com/2014/03/leetcode-gas-station-java/

**

Math， Geedy
**

Anyway, Good luck, Richardo!

My code:

``````public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0 || cost == null || cost.length == 0) {
return -1;
}

int i = 0;
int pre = 0;
int begin = 0;
int end = 0;
while (end < gas.length) {
if (gas[end] + pre >= cost[end]) {
pre += gas[end] - cost[end];
end++;
}
else {
begin = end + 1;
end = begin;
pre = 0;
}
}

if (begin == end) {
return -1;
}
else {
i = begin;
pre = gas[i] - cost[i];
if (pre < 0) {
return -1;
}
i++;
while (i % gas.length != begin) {
pre += gas[i % gas.length] - cost[i % gas.length];
if (pre < 0) {
return -1;
}
i++;
}
return begin;
}

}
}
``````

A如果能到B但不能到C，

Anyway, Good luck, Richardo! -- 09/15/2016