JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

只有一个答案,找到最后一个不可以的点,下一个是开始点

 1 public class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         int total = 0;
 6         int sum = 0;
 7         int startindex = -1;
 8         for(int i = 0; i < gas.length; i++)
 9         {
10             total += (gas[i] - cost[i]);
11             sum += (gas[i] - cost[i]);
12             if(sum < 0)
13             {
14                 sum = 0;
15                 startindex = i;
16             }
17         }
18         return total < 0? -1:startindex + 1;
19     }
20 }

 

posted on 2013-11-09 15:41  JasonChang  阅读(264)  评论(0编辑  收藏  举报