首页 > 其他 > 详细

134. Gas Station

时间:2018-12-06 12:56:41      阅读:146      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/goPanama/p/10076004.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!