【leetCode】134. Gas Station-----Java

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.

最简单的想法是进行循环,复杂度O(n^2)。

我对于此题的理解是,找到一个起点,在行进过程中其gas的和始终是大于cost的和。令over[i] = gas[i]-cost[i](over[i]也就是表示i点的油对未来的行程盈余还是欠缺),就是说over[i]+...+over[k](k从i到i的前一个点变化)始终为正,也就是考虑积累下来的油量是否能够支付以后可能到来的欠缺油量的问题。

如果over[i]+...+over[k] < 0,意味着在i点到k点的部分不会存在起点,这一点比较简单知道。解题就变成了:从0点开始行进,如果一直over和保持为正,结束,起点在0;如果在p点出现负,再从p+1点重新作为起点出发,如果在q点又出现负,就从q+1点出发,找到保持正的点,再去确认其是否保持回到该点仍为正。

按断掉的出发点考虑,sum(i)表示从i点出发到和出现负数(或到数组底)的部分的和,整个路程可能被切成sum(0),...,sum(k)部分,sum(k)就是最后到数组底的部分,sum(0)到sum(k-1)都是负数。如果sum(k)< 0时,所有点都被排除,则不存在起点,也就是sum(0)+...+sum(k)< 0;如果存在起点,则必定是在sum(k)> 0时,此时只要保证sum(0)+...+sum(k)>= 0 ,就证明是存在起点,而且起点是k+1。而sum(0)+...+sum(k)表示的是总的gas和cost的差,所以只要是总gas大于总cost,即总汽油量够支付行程所需汽油量,必定存在一个点可以满足条件。(题中限制解唯一)

我的实现如下:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if(gas.length != cost.length) return -1;
        // 总差额量
        int total = 0;
        // 保存sum
        int temp = 0;
        // 记录起点
        int start = 0;

        for(int i = 0; i < gas.length; i++){
            total = total + gas[i] - cost[i];
            temp = temp + gas[i] - cost[i];
            if(temp < 0){
                start = i + 1;
                temp = 0;
            }
        }
        
        if(total<0) return -1;
        return start;
    }
}

 

转载于:https://my.oschina.net/ruanhang1993/blog/737811

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值