1094. Car Pooling 可以放下所有人嗎
1094. Car Pooling
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity and an array trips where trip[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5 Output: true
Constraints:
1 <= trips.length <= 1000trips[i].length == 31 <= numPassengersi <= 1000 <= fromi < toi <= 10001 <= capacity <= 105
沒想到啥好的作法,但還是過了,最簡單就是搞一個dictionary 針對每一個integer,把當時車上人數加起來,這基本上跟simulate整個過程是一樣的,最後看看在尖峰時間,車上人最多時候有沒有超過capacity,如果有return False
如果沒有return True
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: d=defaultdict(int) for i in trips: num,fro,to=i for j in range(fro,to): d[j]+=num return capacity>=max(d.values())
留言
張貼留言