---
# System prepended metadata

title: 2332. The Latest Time to Catch a Bus
tags: ['2332', leetcode, google]

---

# 2332. The Latest Time to Catch a Bus
###### tags: `leetcode` `2332` `medium` `google`

## :memo:  Question
![](https://hackmd.io/_uploads/Hkt78c7ph.png)

## :memo: 題意
* 給你兩個 array 
    * buses array ex. [1,2,3] 第一台公車離開的時間是1，第二台離開的時間是 2
    * passengers array ex. [2,4,5] 第一位乘客到達的時間是2，第二位乘客到達的時間是4
    * capaciy ex. 每台公車的乘客量
    * 要你求出如果你想搭上公車那最晚什麼時候要到？
    * limits: 
        * Each element in buses is unique.
        * Each element in passengers is unique.

## :memo: leetcode solution
* :medal: **思考一**: 要模擬出搭車的過程


## :memo: my solution code
```python=
class Solution:
    def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:
        
        sort_pa = sorted(passengers)
        ans = 1
        i = 0
        for bus in sorted(buses):
            c = 0
            while i < len(passengers) and sort_pa[i] <= bus and c < capacity:
                
                if i == 0 or (i >= 1 and passengers[i]-passengers[i-1] != 1):
                    ans = passengers[i] - 1
                    
            if c < capacity:
                if i == 0 or (i >= 1 and passengers[i-1] != bus ):
                    ans = bus
        
                    
        return ans
                
```

## :memo: BigO
* 時間複雜度: O(nlogn)。
* 空間複雜度: O(n)。 