1094. Car Pooling
- 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
CarPooling问题的Python解决方案
561

被折叠的 条评论
为什么被折叠?



