LeetCode 题解工作台
设计停车系统
请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。 请你实现 ParkingSystem 类: ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类,三个参数分别对…
3
题型
8
代码语言
3
相关题
当前训练重点
简单 · design·结合·模拟
答案摘要
我们用一个长度为 的数组 来表示停车场中每种车位的数量,其中 , , 分别表示大车位、中车位、小车位的数量。 在初始化时,我们将 , , 分别初始化为大车位、中车位、小车位的数量。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 design·结合·模拟 题型思路
题目描述
请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。
请你实现 ParkingSystem 类:
ParkingSystem(int big, int medium, int small)初始化ParkingSystem类,三个参数分别对应每种停车位的数目。bool addCar(int carType)检查是否有carType对应的停车位。carType有三种类型:大,中,小,分别用数字1,2和3表示。一辆车只能停在carType对应尺寸的停车位中。如果没有空车位,请返回false,否则将该车停入车位并返回true。
示例 1:
输入: ["ParkingSystem", "addCar", "addCar", "addCar", "addCar"] [[1, 1, 0], [1], [2], [3], [1]] 输出: [null, true, true, false, false] 解释: ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // 返回 true ,因为有 1 个空的大车位 parkingSystem.addCar(2); // 返回 true ,因为有 1 个空的中车位 parkingSystem.addCar(3); // 返回 false ,因为没有空的小车位 parkingSystem.addCar(1); // 返回 false ,因为没有空的大车位,唯一一个大车位已经被占据了
提示:
0 <= big, medium, small <= 1000carType取值为1,2或3- 最多会调用
addCar函数1000次
解题思路
方法一:模拟
我们用一个长度为 的数组 来表示停车场中每种车位的数量,其中 , , 分别表示大车位、中车位、小车位的数量。
在初始化时,我们将 , , 分别初始化为大车位、中车位、小车位的数量。
每次停车时,我们检查停车场中是否有对应车位,如果没有则返回 ,否则将对应车位的数量减一,并返回 。
时间复杂度 ,空间复杂度 。
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.cnt = [0, big, medium, small]
def addCar(self, carType: int) -> bool:
if self.cnt[carType] == 0:
return False
self.cnt[carType] -= 1
return True
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) for N addCar calls since each operation is O(1). Space complexity is O(1) because only three counters are stored regardless of N. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if the candidate tracks slot availability correctly for each car type.
- question_mark
Observe whether addCar updates the internal state without overwriting counts.
- question_mark
See if the candidate handles repeated calls after slots are full efficiently.
常见陷阱
外企场景- error
Mixing up car type indices leading to wrong counter updates.
- error
Failing to return false when a slot is already occupied.
- error
Not correctly handling edge cases where initial slots are zero.
进阶变体
外企场景- arrow_right_alt
Extend to support dynamic slot addition and removal after initialization.
- arrow_right_alt
Modify for multiple parking lots with shared cars types across lots.
- arrow_right_alt
Track parking history to determine peak usage per car type.