Created
June 4, 2015 19:42
-
-
Save cangoal/269c4c987aa71b2dc23d to your computer and use it in GitHub Desktop.
LeetCode - Gas Station
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| public int canCompleteCircuit(int[] gas, int[] cost) { | |
| if(gas == null || gas.length == 0 || cost == null || cost.length == 0) return -1; | |
| int total = 0, local = 0, index = 0; | |
| for(int i=0; i<gas.length; i++){ | |
| total += gas[i] - cost[i]; | |
| local += gas[i] - cost[i]; | |
| if(local < 0){ | |
| index = i + 1; // don't write index = i; | |
| local = 0; | |
| } | |
| } | |
| if(total < 0) return -1; | |
| return index; | |
| } | |
| // | |
| public int canCompleteCircuit(int[] gas, int[] cost) { | |
| int len = gas.length, sum=0, total=0, idx=-1; | |
| for(int i=0; i<len; i++){ | |
| sum += gas[i] - cost[i]; | |
| total += gas[i] - cost[i]; | |
| if(sum<0){ | |
| sum=0; | |
| idx=i; | |
| } | |
| } | |
| return total>=0 ? idx+1 : -1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment