134. Gas Station(加油站)

134. Gas Station(加油站)

题目链接

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

题目描述

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.

题目分析

这道题目很容易想到直观的算法:以每一个点作为出发点,尝试是否能走完一圈;若均不能,则没有。时间复杂度为O(n2)
实际上经过分析我们可以发现:若以i为出发点,走到j时无法走到下一个点。对于在ij中的任意一点k,走到k点时剩余油量一定是大于等于0的。所以,如果从i为出发点最多只能走到j,那么从k也最多只能走到j。所以若以i为出发点无法走完一圈时,ij之间的点都可以排除。时间复杂度为O(n)

方法一:暴力

算法描述

从第1个点到最后一个点,以每一个点作为出发点:
  若走到某一个点时不能走到下一个点,则尝试下一个出发点
  若走完一圈,则找到答案
若遍历完所有的出发点都没有找到,则不存在

方法二:跳跃

算法描述

和暴力算法基本一致,只是需要记录在当前尝试中能向前走多少个点,下一次尝试要跳过中间能经过的那些点,以第一个走不到的点作为出发点。

参考代码

方法一:暴力

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        vector<int> Gas, Cost;
        Gas.insert(Gas.end(), gas.begin(), gas.end());
        Gas.insert(Gas.end(), gas.begin(), gas.end());
        Cost.insert(Cost.end(), cost.begin(), cost.end());
        Cost.insert(Cost.end(), cost.begin(), cost.end());
        for (int i = 0; i < gas.size(); i++) {
            bool flag = true;
            for (int j = i, g = 0; j < i + gas.size(); j++) {
                g += Gas[j] - Cost[j];
                if (g < 0) {
                    flag = false;
                    break;
                }
            }
            if (flag)
                return i;
        }
        return -1;
    }
};

方法二:跳跃

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        vector<int> Gas, Cost;
        Gas.insert(Gas.end(), gas.begin(), gas.end());
        Gas.insert(Gas.end(), gas.begin(), gas.end());
        Cost.insert(Cost.end(), cost.begin(), cost.end());
        Cost.insert(Cost.end(), cost.begin(), cost.end());
        int i, j, leftGas;
        for (i = 0; i < gas.size(); i += j - i + 1) {
            bool flag = true;
            for (j = i, leftGas = 0; j < i + gas.size(); j++) {
                leftGas += Gas[j] - Cost[j];
                if (leftGas < 0) {
                    flag = false;
                    break;
                }
            }
            if (flag)
                return i;
        }
        return -1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值