面试经典算法题42-加油站

面试经典算法题42-加油站

公众号:阿Q技术站
LeetCode.134

问题描述

在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

给定两个整数数组 gascost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。

示例 1:

输入: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
输出: 3
解释:
从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。

示例 2:

输入: gas = [2,3,4], cost = [3,4,3]
输出: -1
解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。

思路

  1. 遍历所有加油站,计算每个加油站的净剩余汽油量(gas[i] - cost[i]),并累加到 total 中。
  2. 如果 total 小于 0,则无法完成环行行驶,返回 -1。
  3. 如果 total 大于等于 0,则可以完成环行行驶,接下来找到起始加油站。
  4. 从第一个加油站开始,计算从当前加油站出发,能否到达下一个加油站。如果不能到达,则将起始加油站设为下一个加油站。
  5. 如果能到达下一个加油站,则继续判断能否到达下下个加油站,直到绕完一圈为止。
  6. 返回起始加油站的编号。

图解

今天先把昨天那个图解给大家纠正一下,不知道大家发现了没

         +-------------------+
         |    开始执行程序     |
         +-------------------+
                  |
                  v
    +-----------------------------+
    |   初始化变量:jumps = 0,      |
    |   end = 0, max_pos = 0      |
    +-----------------------------+
                  |
                  v
    +-----------------------------+
    |      第1次循环:i = 0,        |
    |max_pos = max(0, 0 + 2) = 2, |
    | i == end成立 ,jumps = 1     |
    +-----------------------------+
                  |
                  v
    +-----------------------------+
    |     第2次循环:i = 1,         |
    |max_pos = max(2, 1 + 3) = 4, |
    |     i == end 不成立          |
    +-----------------------------+
                  |
                  v
    +-----------------------------+
    |      第3次循环:i = 2,        |
    |max_pos = max(4, 2 + 1) = 4, |
    |  i == end 成立,jumps = 2    |
    +-----------------------------+
                  |
                  v
  +--------------------------------+
  |      第4次循环:i = 3,           |
  | max_pos = max(4, 3 + 1) = 4,   |
  |	       i == end 不成立          |
  +--------------------------------+
                  |
                  v
    +-----------------------------+
    |   循环结束,返回 jumps = 2    |
    +-----------------------------+

然后再看今天的流程图解:

          +-------------------------+
          |        开始执行程序       |
          +-------------------------+
                      |
                      v
          +-------------------------+
          |        初始化变量         |
          |       total = 0         |
          |       current = 0       |
          |       start = 0         |
          +-------------------------+
                      |
                      v
          +-------------------------+
          |     循环处理每个加油站     |
          +-------------------------+
                      |
                      v
        +-------------------------------+
        |        当前加油站 0:           |
        |   total += gas[0] - cost[0]   |
        |   current += gas[0] - cost[0] |
        |   current = 1, total = -2     |
        +-------------------------------+
                      |
                      v
        +-------------------------------+
        |        当前加油站 1:           |
        |   total += gas[1] - cost[1]   |
        |   current += gas[1] - cost[1] |
        |   current = 0, total = -3     |
        +-------------------------------+
                      |
                      v
        +--------------------------------+
        |       当前加油站 2:             |
        |   total += gas[2] - cost[2]    |
        |   current += gas[2] - cost[2]  |
        |   current = 0, total = -5      |
        +--------------------------------+
                      |
                      v
        +-------------------------------+
        |      当前加油站 3:             |
        |   total += gas[3] - cost[3]   |
        |   current += gas[3] - cost[3] |
        |   current = 4, total = -4     |
        +-------------------------------+
                      |
                      v
        +------------------------------+
        |       当前加油站 4:           |
        |   total += gas[4] - cost[4]  |
        |   current += gas[4] - cost[4]|
        |   current = 7, total = 1     |
        +------------------------------+
                      |
                      v
  +-----------------------------------------+
  |           判断是否能完成环行行驶            |
  |   total >= 0,返回起始加油站编号 start = 3  |
  +-----------------------------------------+
                      |
                      v
         +-------------------------+
         |         结束程序         |
         +-------------------------+

参考代码

C++
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        int total = 0;
        int sum = 0;
        int start = 0;

        for (int i = 0; i < n; ++i) {
            total += gas[i] - cost[i]; // 计算净剩余汽油量
            sum += gas[i] - cost[i];   // 计算从起点到当前加油站的净剩余汽油量

            if (sum < 0) {  // 如果当前净剩余汽油量为负,说明无法从起点出发到达当前加油站
                start = i + 1;  // 将起点设为下一个加油站
                sum = 0;        // 重置 sum
            }
        }

        return total >= 0 ? start : -1; // 如果总净剩余汽油量大于等于 0,则可以完成环行行驶,返回起始加油站编号,否则返回 -1
    }
};

int main() {
    vector<int> gas = {1, 2, 3, 4, 5};
    vector<int> cost = {3, 4, 5, 1, 2};
    Solution solution;
    int result = solution.canCompleteCircuit(gas, cost);
    cout << "起始加油站编号:" << result << endl;

    return 0;
}
Java
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int total = 0;
        int sum = 0;
        int start = 0;

        for (int i = 0; i < n; ++i) {
            total += gas[i] - cost[i]; // 计算净剩余汽油量
            sum += gas[i] - cost[i];   // 计算从起点到当前加油站的净剩余汽油量

            if (sum < 0) {  // 如果当前净剩余汽油量为负,说明无法从起点出发到达当前加油站
                start = i + 1;  // 将起点设为下一个加油站
                sum = 0;        // 重置 sum
            }
        }

        return total >= 0 ? start : -1; // 如果总净剩余汽油量大于等于 0,则可以完成环行行驶,返回起始加油站编号,否则返回 -1
    }

    public static void main(String[] args) {
        int[] gas = {1, 2, 3, 4, 5};
        int[] cost = {3, 4, 5, 1, 2};
        Solution solution = new Solution();
        int result = solution.canCompleteCircuit(gas, cost);
        System.out.println("起始加油站编号:" + result);
    }
}
Python
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas)
        total = 0
        current = 0
        start = 0

        for i in range(n):
            total += gas[i] - cost[i]  # 计算净剩余汽油量
            current += gas[i] - cost[i]  # 计算从起点到当前加油站的净剩余汽油量

            if current < 0:  # 如果当前净剩余汽油量为负,说明无法从起点出发到达当前加油站
                start = i + 1  # 将起点设为下一个加油站
                current = 0  # 重置当前净剩余汽油量

        return start if total >= 0 else -1  # 如果总净剩余汽油量大于等于 0,则可以完成环行行驶,返回起始加油站编号,否则返回 -1

# 示例用法
gas = [1, 2, 3, 4, 5]
cost = [3, 4, 5, 1, 2]
solution = Solution()
result = solution.canCompleteCircuit(gas, cost)
print("起始加油站编号:", result)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值