`
ouqi
  • 浏览: 41324 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Gas Station

阅读更多

Gas Station

 
AC Rate: 296/1493

 

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
The solution is guaranteed to be unique.

 

思路:

1 计算c[i] = gas[i] - cost[i] 表示i 到i+1的汽油增量。

2 则本题为:汽车从任意点 i 出发,油量增增减减,但过程中必须保证油量>=0

3 设置delta表示汽车油量,初始为0;  注意到,假设汽车从i点出发,第一次delta+c[j]<0  (即汽车行至j点与j+1的半路中没油了 );则从i+1 到 j 的范围内,以任意一个做为起始点都是不ok的。即下一个可能的起始点从j+1开始。因为: 

       delta+c[j]第一次小于0, 说明 在i 到 j-1的范围内 delta都是大于0的,若以这中间任意一点m作为起始点,则delta =delta+c[j] - i到m间的油量(肯定>=0),所以最终delta也是小于0的;

4. 用于start记录起始点,last记录上一可能的起始点,由上述分析可知 last 至 start-2的范围内肯定是大于等于0的(start-1导致的<0);所以对于start,需要从start一直循环遍历到last并且加上start-1。

 

代码:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        //各种异常
        if(gas == null||cost == null) return -1;
        int len = gas.length;
        if(cost.length!=len) return -1;
        
        int c[] = new int[len];
        for(int i = 0;i<=len-1;i++)
            c[i] = gas[i]-cost[i];
        
        int delta = 0;
        int j = 0;
        int last = 0;
        int start = 0;
        while(start<=len-1&&j<=len-1){
            delta = delta + c[j];
            if(delta<0){
                delta = 0;
                last = start;
                start = j+1; 
            }
            j++;
        }
        if(start == len) return -1;
        //确认以start为开始是否可以跑完全程
        for(int i = 0;i<last;i++) delta = delta+c[i];
        if(start >= 1) delta = delta+c[start-1];
        if(delta>=0) return start;
        return -1;
        
    }
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics