Easy
题目描述
为停车场设计一个停车系统。停车场有三种类型的停车位:大型、中型和小型,每种类型都有固定数量的车位。
实现 ParkingSystem 类:
ParkingSystem(int big, int medium, int small)初始化ParkingSystem类的对象。每种停车位的数量作为构造函数的参数给出。bool addCar(int carType)检查是否有carType对应的停车位可以停放要进入停车场的车。carType有三种类型:大型、中型或小型,分别用数字1、2和3表示。一辆车只能停在对应类型的停车位中。如果没有空位可用,返回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次
解题思路
这是一道经典的设计题,核心思路非常直接:维护三种停车位的剩余数量。
基本思路:
- 在构造函数中,保存三种停车位的初始数量
- 在
addCar方法中,根据车型检查对应停车位是否还有剩余 - 如果有剩余,减少对应类型的停车位数量并返回
true - 如果没有剩余,直接返回
false
实现细节:
- 可以用三个变量分别存储大型、中型、小型停车位的剩余数量
- 也可以用数组存储,通过下标访问(注意车型从1开始编号)
- 每次停车成功后,对应类型的剩余数量减1
这道题的关键在于正确理解题意和维护状态。由于操作简单,时间复杂度为O(1),空间复杂度也是O(1)。这是一道很好的面向对象设计入门题,考查的是基本的类设计和状态维护能力。
推荐解法: 使用三个成员变量分别存储三种停车位的剩余数量,代码清晰易懂。
代码实现
class ParkingSystem {
private:
int big, medium, small;
public:
ParkingSystem(int big, int medium, int small) : big(big), medium(medium), small(small) {
}
bool addCar(int carType) {
if (carType == 1) {
if (big > 0) {
big--;
return true;
}
} else if (carType == 2) {
if (medium > 0) {
medium--;
return true;
}
} else if (carType == 3) {
if (small > 0) {
small--;
return true;
}
}
return false;
}
};
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.spaces = [0, big, medium, small] # 索引0不使用,1-3对应车型
def addCar(self, carType: int) -> bool:
if self.spaces[carType] > 0:
self.spaces[carType] -= 1
return True
return False
public class ParkingSystem {
private int big, medium, small;
public ParkingSystem(int big, int medium, int small) {
this.big = big;
this.medium = medium;
this.small = small;
}
public bool AddCar(int carType) {
switch (carType) {
case 1:
if (big > 0) {
big--;
return true;
}
break;
case 2:
if (medium > 0) {
medium--;
return true;
}
break;
case 3:
if (small > 0) {
small--;
return true;
}
break;
}
return false;
}
}
var ParkingSystem = function(big, medium, small) {
this.spaces = [0, big, medium, small]; // 索引0不使用,1-3对应车型
};
ParkingSystem.prototype.addCar = function(carType) {
if (this.spaces[carType] > 0) {
this.spaces[carType]--;
return true;
}
return false;
};
复杂度分析
| 操作 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| 构造函数 | O(1) | O(1) |
| addCar | O(1) | O(1) |
| 总体 | O(1) | O(1) |