1094.拼车

【LetMeFly】1094.拼车:优先队列

力扣题目链接:https://leetcode.cn/problems/car-pooling/

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

给定整数 capacity 和一个数组 trips ,  trip[i] = [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
  • trips[i].length == 3
  • 1 <= numPassengersi <= 100
  • 0 <= fromi < toi <= 1000
  • 1 <= capacity <= 105

方法一:优先队列

首先二话不说对trips按“上车地点”为依据从小到大排个序。

接着创建一个优先队列,用于存放“已上车的人”。优先队列的排序依据是“先下车的人优先”。

使用一个变量记录当前车上的人数,遍历trips数组:

让优先队列中,不晚于此位置的人下车;

让这批人上车。

期间若出现超载的情况则返回false,否则返回true

  • 时间复杂度$O(n\log n)$,其中$n=len(trips)$
  • 空间复杂度$O(n)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
sort(trips.begin(), trips.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});
int nowPeopleCnt = 0;
auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> nowPeople(cmp);
for (vector<int>& trip : trips) {
int num = trip[0], from = trip[1], to = trip[2];
while (nowPeople.size() && nowPeople.top().second <= from) {
nowPeopleCnt -= nowPeople.top().first;
nowPeople.pop();
}
nowPeopleCnt += num;
if (nowPeopleCnt > capacity) {
return false;
}
nowPeople.push({num, to});
}
return true;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# from typing import List
# import heapq

class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips.sort(key=lambda x: x[1])
nowPeopleCnt = 0
nowPeople = []
for num, from_, to in trips:
while nowPeople and nowPeople[0][0] <= from_:
nowPeopleCnt -= nowPeople[0][1]
heapq.heappop(nowPeople)
nowPeopleCnt += num
if nowPeopleCnt > capacity:
return False
heapq.heappush(nowPeople, (to, num))
return True

同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/134751973


1094.拼车
https://blog.letmefly.xyz/2023/12/02/LeetCode 1094.拼车/
作者
Tisfy
发布于
2023年12月2日
许可协议