1094. Car Pooling 可以放下所有人嗎

 1094Car 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 <= 1000
  • trips[i].length == 3
  • 1 <= numPassengersi <= 100
  • 0 <= fromi < toi <= 1000
  • 1 <= 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())

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起