2.1.21 Gas Station

Link: https://oj.leetcode.com/problems/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.

Note:
The solution is guaranteed to be unique.

我的思路:需要两个条件:

1 加油站油的总量不小于耗油总量:sum(gas[i]) >= sum(cost[i])

2 从加油站i 到i+1: //这部分不会写。如果start != 0, 怎样遍历循环数组? i.e. start = 2, gas[0], gas[1]如何访问?

如果i == start 是起始点:gas[i] - cost[i] >=0

如果不是:gas[i]-cost[i]+gas[i+1] >= cost[i+1]

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sumGas = 0;
        int sumCost = 0;
        for(int i = 0; i < gas.length; i++){
            sumGas += gas[i];
            sumCost += cost[i];
        }
        if(sumGas < sumCost) return -1;
        int i = 0;
        for(int i = 0; )
    }
}

思路基本正确,但还不够清楚。再做。

正确思路:设两个量,一个是当前序列的累计油量sum,一个是总的累积油量total。有解的充分必要条件是:sum>=0 && total>=0

证明见:http://blog.csdn.net/linhuanmars/article/details/22706553 (没有完全看懂)

Time: O(n), Space: O(1)

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int total = 0;
        int j = 0;//start station index
        for(int i = 0; i < gas.length; i++){
            int diff = gas[i] - cost[i];
            sum += diff;
            if(sum < 0){//cannot reach gas station i+1, start from next station
                j = i+1;
                sum = 0;
            }
            total += diff;
        }
        return total >=0 ? j : -1;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值