134. Gas Station java solutions

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

 1 public class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         if(gas.length == 0 || cost.length == 0 || gas.length != cost.length) return -1;
 4         int total = 0,sum = 0,ans = 0;
 5         for(int i = 0; i < gas.length; i++){
 6             total += (gas[i] - cost[i]);
 7             if(sum < 0){
 8                 sum = gas[i] - cost[i];
 9                 ans = i;
10             }else{
11                 sum += (gas[i] - cost[i]);
12             }
13         }
14         return total >= 0 ? ans:-1; 
15     }
16 }

参考思路:

http://www.cnblogs.com/felixfang/p/3814463.html

原文地址:https://www.cnblogs.com/guoguolan/p/5638626.html