0
点赞
收藏
分享

微信扫一扫

LeetCode 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 ) 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++
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
# 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
举报

相关推荐

0 条评论