码迷,mamicode.com
首页 > 其他好文 > 详细

134. Gas Station

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

标签:etc   int   []   ++   problems   i+1   can   col   problem   

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

标签:etc   int   []   ++   problems   i+1   can   col   problem   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!