LeetCodeP134 Gas Station

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.

题目大意:gas[i]代表当前汽油站的汽油量,cost[i]代表从第i站到第i+1站需要耗费的汽油。开始你的汽车没有油,你能否选择一个站出发,然后环绕一圈回到原点。

思路:

详细的解答请参考转自此处

按常规思路来说,循环遍历数组,如果i站出发不行,那就换i+1站。如果从i站出发,在到达第k站之前油箱都不空,但到达k站后油箱空了,说明从i站开始无法绕一圈,但是我们不必从i+1重新遍历,因为从i站到k站油箱会空,那么从ik站之间的任何一个站都到不了k站。所以我们选择从k+1站开始遍历。如下:

使用一个数组diff[]记录当前站汽油量和消耗量的差值:diff[i] = gas[i]-cost[i]

假设从第一站开始到第p站油箱变空,那么sum1=diff[0]+diff[1]+…+diff[p]<0.

此时,按照我们的思路应该从p+1站开始走,假设从p+1q站油箱又空了,即sum2=diff[p+1]+diff[p+2]+…+diff[q]<0.

那么我们再从q+1开始,假设从q+1到未开始循环的最后一个站时油箱不空,那么sum3=diff[q+1]+diff[q+2]+diff[size-1] > 0.此时我们看能否开会q站,只需看sum3diff[0]加到diff[p]的过程中是否一直非负。因此我们只需看sum1+sum2+sum3是否大于等于0.而sum1+sum2+sum3就是整个diff数组的累加和,所以如果diff数组累加和大于等于零,就一定存在一个元素,从这个元素出发,绕数组一圈,能保证累加和一直非负。

代码:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int index = 0;
        int total = 0, sum = 0;
        if (gas.length == 0 || gas.length != cost.length) {
            return -1;
        }
        for (int i = 0; i < gas.length; i++) {
            total += gas[i] - cost[i];
            if (sum < 0) {
                sum = gas[i] - cost[i];
                index = i;
            } else {
                sum += gas[i] - cost[i];
            }
        }
        return total >= 0 ? index : -1;
    }
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值