LeetCode 134. Gas Station

问题

https://leetcode.com/problems/gas-station/

解法

首先有两个性质:

1, If car starts at A and can not reach B. Any station between A and B
can not reach B.(B is the first station that A can not reach.)
2, If the total number of gas is bigger than the total number of cost. There must be a solution.

1, 很容易证明, 如果station s 位于A, B 之间, 则从A到s 时 tank >= 0, 如果从s出发,则tank = 0, 显然从s 出发不能到达B
2, 首先预处理出Delt[] = gas[] - cost[], 则Delt 表示到每个站tank 变化情况。由于所有cost 之和 小于 gas 之和, 因此 Delt 之和 >= 0.假设下面程序运行后ret == n, 则表示Delt 之和< 0 , 与假设矛盾, 因此ret 必然小于n;

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int tank = 0;
        int delt = 0;
        int ret = 0;
        for (int i=0; i<gas.size(); ++i)
        {
            tank+= gas[i] - cost[i];
            delt += gas[i] - cost[i];
            if (tank < 0)
            {
                ret = i+1;
                tank = 0;
            }
        }
        return delt >=0 ? ret:-1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值