[LeetCode]---Gas Station

题目描述

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].

You have a car with an unlimited gas tank and it costscost[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.

分析

> 首先这道题需要解决两个问题1,能否绕一圈;2,如果能,起点在哪?
>定义数组arr,arr[i]=gas[i]-cost[i] (0<=i <n)
>第一个问题很好解决,遍历数组arr求和,大于0则说明能够转一圈,O(N)的时间复杂度
>第二个问题,假设sum[i,j]= ∑diff[k]  ,如果sum[i,j]<0,说明i肯定不是起点,假设s为[0,n]的解,可以推断sum[k,s-1](0=<k<=s-1)肯定是小于0的(否则解就为k),同理,sum[s,n]一定是大于0的,否则解就不是s,而是k和n之间的一个点,那么问题就可以转化为,在s和n之间找到第一个以n为终点的子序列,子序列和必须大于0
>结合起来,这两个问题就可以在一个循环内解决了

代码如下:

 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) 
 {

        vector<int> arr;
        for(int i=0;i<gas.size();i++)
            {
            arr.push_back(gas[i]-cost[i]);
        }
        int totle=0;
        int sum=0;
        int index=0;
        for(int i=0;i<gas.size();++i)
            {
            sum+=arr[i];
            totle+=arr[i];
            if(sum<0)
                {
                sum=0;
                index=i+1;
            }
        }
        return totle>=0?index:-1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值