leetcode 134. 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.

从0开始以其为起点实验,累加 restGas += gas[i] - cost[i],一旦在 i 处遇到restGas<0,那么就说明当前选择的起点beg不行,需要重新选择,此时我们不应该回去使用 beg+1 作为新起点,遍历到 size-1 处就可以结束了,如果找到了可能的起点,我们还要进行验证,走一遍(total)。

其实本质就是:这个起点将路径分为前后两段,前段总的余量为负,即油不够用,要想有解,那么后段油量应该为正,此时才可能有解,我们要做的就是找到这个分割点作为起点,然后再验证一下;反之,如果前段就为正了,那么显然可以直接选择前面的点为起点;如果整段加起来都是负的,那么无解。

这道题很简单,但是需要好好学习一下!

代码如下:


/*
 * 我们从0开始以其为起点实验,累加 restGas += gas[i] - cost[i],一旦在 i 处遇到restGas<0,
 * 那么就说明当前选择的起点beg不行,需要重新选择,此时我们不应该回去使用 beg+1 作为新起点,
 * 因为在beg处,一定有 gas>=cost,说明 beg+1 到 i 处的总gas一定小于总的cost,
 * 选择其中任何一个作为起点还是不行的,所以应该跳过这些点,以 i+1 作为新起点,
 * 遍历到 size-1 处就可以结束了,如果找到了可能的起点,我们还要进行验证,走一遍(total),
 * 如果没问题那么说明可以。

 * 其实本质就是:这个起点将路径分为前后两段,前段总的余量为负,
 * 即油不够用,要想有解,那么后段油量应该为正,此时才可能有解,
 * 我们要做的就是找到这个分割点作为起点,然后再验证一下;反之,
 * 如果前段就为正了,那么显然可以直接选择前面的点为起点;如果整段
 * 加起来都是负的,那么无解
 * 
 * */
public class Solution 
{
     public int canCompleteCircuit(int[] gas, int[] cost) 
     {
        if(gas == null)
            return -1;
        int start=0,total=0,debt=0;
        for(int i=0;i<gas.length;i++)
        {
            total+=gas[i]-cost[i];
            debt+=gas[i]-cost[i];
            if(debt<0)
            {
                start=i+1;
                debt=0;
            }
        }       
        return total<0 ? -1 :start;
    }
}

下面是C++的做法,就是做一次遍历

代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <climits>

using namespace std;

class Solution 
{
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) 
    {
        if (gas.size() <= 0)
            return -1;
        int total = 0, debt = 0;
        int start = 0;
        for (int i = 0; i < gas.size(); i++)
        {
            total += gas[i] - cost[i];
            debt += gas[i] - cost[i];
            if (debt < 0)
            {
                start = i + 1;
                debt = 0;
            }
        }
        return total < 0 ? -1 : start;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值