加油站

题目:

环形路上有n个加油站,第i个加油站的汽油量是gas[i].
你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。
求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。
注意:
答案保证唯一。

示例:

输入:[2, 3, 1], [3, 1, 2]    输出:1

代码:

 1 import java.util.*;
 2 
 3 
 4 public class Solution {
 5     /**
 6      * 
 7      * @param gas int整型一维数组 
 8      * @param cost int整型一维数组 
 9      * @return int整型
10      */
11     public int canCompleteCircuit (int[] gas, int[] cost) {
12         // write code here
13         int start = gas.length - 1;
14         int end = 0;
15         int sum = gas[start] - cost[start];
16         while( start > end ){
17             if( sum > 0 ){
18                 sum += gas[end] - cost[end];
19                 end ++;
20             }else {
21                 start --;
22                 sum += gas[start] - cost[start];
23             }
24         }
25         return sum >= 0 ? start : -1;
26     }
27 }

笔记:  

  从 start 出发,如果油量足够,则一直向后走,即 end ++。如果油量不够,则需要向后退,即 start ++。最终,在 start == end 的时候,如果有解贼一定是当前 start 在的位置。

 

posted @ 2020-09-19 16:14  John_yan15  阅读(135)  评论(0编辑  收藏  举报