LeetCode 1094. Car Pooling 解题报告(python)

CarPooling问题的Python解决方案

1094. Car Pooling

  1. Car Pooling python solution

题目描述

You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)

Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.

Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

在这里插入图片描述

解析

题目本身比较好理解,就是乘客上车。有人上有人下,车辆是单向行驶,问能否装下所有乘客。
有种比较巧妙的思路,将三元组(n,start,end)变成两个二元组分别为(start,n)和(end,-n)。这样就可以表示每站上下车的人数。
再利用一个新的数组存储这个二元组,然后从小到大排序,即逐站计算。看看在每一站是否会超员。

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        ls=[]
        for n, start, end in trips:
            ls.append((start,n))
            ls.append((end,-n))
        ls.sort()
        par=0
        for i in ls:
            par+=i[1]
            if par> capacity:
                return False
        return True
        

Reference

https://leetcode.com/problems/car-pooling/discuss/319088/Simple-Python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值