【LetMeFly】1094.拼车:优先队列
力扣题目链接:https://leetcode.cn/problems/car-pooling/
车上最初有 capacity
个空座位。车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向)
给定整数 capacity
和一个数组 trips
, trip[i] = [numPassengers
~i~, from
~i~, to
~i~]
表示第 i
次旅行有 numPassengers
~i~ 乘客,接他们和放他们的位置分别是 from
~i~ 和 to
~i~ 。这些位置是从汽车的初始位置向东的公里数。
当且仅当你可以在所有给定的行程中接送所有乘客时,返回 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 <= numPassengers
~i~<= 100
0 <= from
~i~< to
~i~<= 1000
1 <= capacity <= 10
^5^
方法一:优先队列
首先二话不说对trips按"上车地点"为依据从小到大排个序。
接着创建一个优先队列,用于存放"已上车的人"。优先队列的排序依据是"先下车的人优先"。
使用一个变量记录当前车上的人数,遍历trips数组:
让优先队列中,不晚于此位置的人下车;
让这批人上车。
期间若出现超载的情况则返回false
,否则返回true
。
- 时间复杂度 O ( n log n ) O(n\log n) O(nlogn),其中 n = l e n ( t r i p s ) n=len(trips) n=len(trips)
- 空间复杂度 O ( n ) O(n) O(n)
AC代码
C++
cpp
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
python
# 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