134. Gas Station

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了134. Gas Station相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/gas-station/discuss/42591/java-greedy-solution

 

 1 class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         if(gas.length == 0) return -1;
 4         int sum = 0;
 5         int start = 0;
 6         for(int i = 0; i < gas.length; i++){
 7             sum += gas[i] - cost[i];
 8             if(sum < 0){
 9                 sum = 0;
10                 start = i+1;
11                 if(start == gas.length) return -1;
12             }
13         }
14         sum = 0;
15         for(int i = 0; i < gas.length; i++){
16             sum += gas[(start+i) % gas.length] - cost[(start+i) % gas.length];
17             if(sum < 0) return -1;
18         }
19         return start;
20         
21     }
22 }

 

以上是关于134. Gas Station的主要内容,如果未能解决你的问题,请参考以下文章

134.Gas Station

134. Gas Station

134. Gas Station(js)

134. Gas Station

134. Gas Station

134. Gas Station