[LeetCode] Gas Station

203 篇文章 0 订阅

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.

解题思路:

这套题的题意为,有N个汽油站排成一个环。gas[i]表示第i个汽油站的汽油量,cost[i]表示第i个汽油站到第i+1个汽油站所需要的汽油。假设汽车油箱无限大。那么求出能够让汽车环行一周的一个起始汽油站序号。若不存在,返回-1。

解法1:

两次循环,分别测试每个站点,看是否能够环行一周即可。时间复杂度为O(n^2)。大数据产生超时错误。

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int len = gas.size();
        if(len!=cost.size()){
            return -1;
        }
        for(int i=0; i<len; i++){
            int left = gas[i] - cost[i];
            int j = (i+1)%len;
            while(j!=i && left >=0){
                left += gas[j] - cost[j];
                j = (j+1)%len;
            }
            if(left>=0){
                return i;
            }
        }
        return -1;
    }
};
解法2:

水中的鱼的博客中讲述的http://fisherlei.blogspot.com/2013/11/leetcode-gas-station-solution.html。

在任何一个节点,其实我们只关心油的损耗,定义: 

diff[i] = gas[i] – cost[i]  0<=i <n 

那么这题包含两个问题: 

1. 能否在环上绕一圈? 

2. 如果能,这个起点在哪里? 

第一个问题,很简单,我对diff数组做个加和就好了,leftGas = ∑diff[i], 如果最后leftGas是正值,那么肯定存在这么一个起始点。如果是负值,那说明,油的损耗大于油的供给,不可能有解。得到第一个问题的答案只需要O(n)。 

对于第二个问题,起点在哪里? 

假设,我们从环上取一个区间[i, j], j>i, 然后对于这个区间的diff加和,定义 

sum[i,j] = ∑diff[k] where i<=k<j 

如果sum[i,j]小于0,那么这个起点肯定不会在[i,j]这个区间里,跟第一个问题的原理一样。举个例子,假设i是[0,n]的解,那么我们知道 任意sum[k,i-1] (0<=k<i-1) 肯定是小于0的,否则解就应该是k。同理,sum[i,n]一定是大于0的,否则,解就不应该是i,而是i和n之间的某个点。所以第二题的答案,其实就是在0到n之间,找到第一个连续子序列(这个子序列的结尾必然是n)大于0的。 

至此,两个问题都可以在一个循环中解决。 

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



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值