LeetCode OJ:Gas Station

Gas Station

  Total Accepted: 5589  Total Submissions: 23851 My Submissions

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.


算法思想:以gas[i]-cost[i]为考虑对象,此题也就是找出可以从该点出发一直加到该点的前一点,其中不会出现小于0的点,一种比较直白的方式是把每个点都这么找一遍来确定答案,其实可以这么考虑,若所有这些点的和sum>=0,说明必定可以找到满足题目的一点,既然如此,

假设序列a1,a2,a3.....ai,a(i+1)....an,若有a1+a2+..+ai<0,则必然有a(i+1)+..+an>0(否则不满足sum>=0)且|a(i+1)+..+an|>=|a1+a2+...+ai|,那么我们只需找到使sum和最小的那个点的后一个点,则必然可以满足,从这个点开始,总能保证sum>=0

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int sum=0;
        int index=0,val=0;
        for(int i=0;i<gas.size();i++){
            sum+=gas[i]-cost[i];
            if(sum<val){
                val=sum;
                index=i+1;
            }
        }
        if(sum>=0){
            return index%gas.size();
        }
        return -1;
    }
};

answer2

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int total=0;
        int j=-1;
        for(int i=0,sum=0;i<gas.size();++i){
            sum+=gas[i]-cost[i];
            total+=gas[i]-cost[i];
            if(sum<0){
                j=i;
                sum=0;
            }
        }
        return total>=0?j+1:-1;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值