题目描述
请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。
请你实现 ParkingSystem 类:
ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类,三个参数分别对应每种停车位的数目。
bool addCar(int carType) 检查是否有 carType 对应的停车位。 carType 有三种类型:大,中,小,分别用数字 1, 2 和 3 表示。一辆车只能停在 carType 对应尺寸的停车位中。如果没有空车位,请返回 false ,否则将该车停入车位并返回 true 。
示例
输入:
["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 <= 1000
carType 取值为 1, 2 或 3
最多会调用 addCar 函数 1000 次
白银段位之简单变量
直接使用几个成员变量来记录 。
class ParkingSystem {
public:
int b, m, s;
ParkingSystem(int big, int medium, int small): b(big), m(medium), s(small) {}
bool addCar(int ct) {
if (ct == 1 && b > 0) return b-->0;
else if (ct == 2 && m > 0) return m-->0;
else if (ct == 3 && s > 0) return s-->0;
return false;
}
};
时间复杂度:O(1)
空间复杂度:O(1)
黄金段位之数组
更好的方法是使用数组来进行记录。当增加车类型,只需要重载一个构造方法即可。
class ParkingSystem {
public:
int m[4];
ParkingSystem(int big, int medium, int small) {
m[1] = big;
m[2] = medium;
m[3] = small;
}
bool addCar(int ct) {
if (ct == 1 && m[1] > 0) return m[1]-->0;
else if (ct == 2 && m[2] > 0) return m[2]-->0;
else if (ct == 3 && m[3] > 0) return m[3]-->0;
return false;
}
};
时间复杂度:O(1)
空间复杂度:O(1)
铂金段位之二进制分段
JDK 中的 ThreadPoolExecutor 使用了一个 ctl 变量 (int 类型) 的前 33 位记录线程池的状态,后 29 位记录程池中线程个数。
当线程数量变化为某个特定值时,要修改的就不仅仅是线程数量,还需要修改线程池的状态。
由于并发环境下,如果要做到原子性地同时需要修改两个 int 的话。只能上重量级锁,重量级锁就会涉及到内核态的系统调用,通常是耗时是用户态的上百倍。
如果我们将线程数量和线程池的状态合二为一之后,我们只需要修改一个 int,这时候只需要使用 CAS 做法(用户态)即可保证线程安全与原子性,性能也得到了提升。
如果我们允许同时停入不同类型的车,在不引入重量级锁的前提下,想要实现同时修改两种类型的车的车位,可以采用二进制分段做法 。1000 的二进制表示只有 10 位,一个 int 有 32 位,因此我们可以使用一个 int 配合位运算来分段做。使用 [0,10)代表 big,[10,20) 表示 medium,[20,30) 表示 small。
class ParkingSystem {
int cnt; // [small medium big]
public ParkingSystem(int _big, int _medium, int _small) {
for (int i = 0; i < 30; i++) {
int cur = 0;
if (i < 10) {
cur = (_big >> i) & 1;
} else if (i < 20) {
cur = (_medium >> (i - 10)) & 1;
} else if (i < 30) {
cur = (_small >> (i - 20)) & 1;
}
cnt += cur == 1 ? (1 << i) : 0;
}
}
public boolean addCar(int ct) {
int cur = countOfType(ct);
if (cur > 0) {
setCount(ct, cur - 1);
return true;
}
return false;
}
int countOfType(int ct) {
int ans = 0;
int start = --ct * 10, end = start + 10;
for (int i = start; i < end; i++) {
if (((cnt >> i) & 1) == 1) {
ans += (1 << (i - start));
}
}
return ans;
}
void setCount(int ct, int pc) {
int start = --ct * 10, end = start + 10;
for (int i = start; i < end; i++) {
if (((pc >> (i - start)) & 1) == 1) {
cnt |= (1 << i);
} else {
cnt &= ~(1 << i);
}
}
}
}