LeetCode 每日一题 Day1

1094. 拼车

车上最初有 capacity 个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向)

给定整数 capacity 和一个数组 trips , tripi = numPassengersi, fromi, toi 表示第 i 次旅行有 numPassengersi 乘客,接他们和放他们的位置分别是 fromi 和 toi 。这些位置是从汽车的初始位置向东的公里数。

当且仅当你可以在所有给定的行程中接送所有乘客时,返回 true,否则请返回 false。

示例 1:

输入:trips = \[2,1,5,3,3,7], capacity = 4

输出:false

示例 2:

输入:trips = \[2,1,5,3,3,7], capacity = 5

输出:true

提示:

1 <= trips.length <= 1000

tripsi.length == 3

1 <= numPassengersi <= 100

0 <= fromi < toi <= 1000

1 <= capacity <= 105

我的代码实现如下,使用了差分法:

复制代码
#include <iostream>
#include <vector>

bool carPooling(std::vector<std::vector<int>>& trips, int capacity) {
    const int maxLocation = 1001; // 最大位置数,根据题目要求设定

    // 创建差分数组,初始化为0
    std::vector<int> diff(maxLocation, 0);

    // 更新差分数组
    for (const auto& trip : trips) {
        diff[trip[1]] += trip[0]; // 乘客在 fromi 上车
        diff[trip[2]] -= trip[0]; // 乘客在 toi 下车
    }

    // 模拟行车过程,并实时检查是否超过最大载客量
    int currentPassengers = 0;
    for (int i = 0; i < maxLocation; ++i) {
        currentPassengers += diff[i];
        if (currentPassengers > capacity) {
            return false; // 在某个时刻超过了最大载客量
        }
    }

    return true;
}

int main() {
    std::vector<std::vector<int>> trips = {{4, 5, 6}, {6, 4, 7}, {4, 3, 5}, {2, 3, 5}};
    int capacity = 13;
    bool result = carPooling(trips, capacity);
    std::cout << std::boolalpha << result << std::endl; // 输出 true

    return 0;
}

在这里给出了完整代码,至于使用差分法,是因为它可以高效处理数组元素的区间修改,正好与该题对应,使用迭代差分即可ac

相关推荐
aaaameliaaa3 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管4 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯4 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡5 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯5 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang5 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9855 小时前
高进度算法模板速记(待完善)
java·前端·算法
圣保罗的大教堂8 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
土豆.exe8 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法
黄河123长江8 小时前
有限Abel群的结构()
算法