设计停车系统
题目:
首先来分析题目,判断是否有车位返回true和false,很直接的想法就是我们去生成三个计数器,去判断计数器对应的值是否为0,是就说明车位已经空了,不是就说明车位还可以停,然后把计数器-1就可以了。
代码如下:
class ParkingSystem {
int big,medium,small;
public ParkingSystem(int big, int medium, int small) {
this.big = big;
this.medium = medium;
this.small=small;
}
public boolean addCar(int carType) {
if(carType==1){
if(big>0){
big--;
return true;
}else{
return false;
}
}else if(carType==2){
if(medium>0){
medium--;
return true;
}else{
return false;
}
}else{
if(small>0){
small--;
return true;
}else{
return false;
}
}
}
}
leetcode运行结果:
反过来想想,我们订好了这个容器的大小3(大车,中车,小车),变的是停的车,也就是这个容器里面的value,所以自然而然的会有另一种想法,HASHMAP
代码如下:
Map<Integer, Integer> map = new HashMap<>();
public ParkingSystem(int big, int medium, int small) {
map.put(1, big);
map.put(2, medium);
map.put(3, small);
}
public boolean addCar(int carType) {
if (map.get(carType) > 0) {
map.put(carType, map.get(carType) - 1);
return true;
}
return false;
}
简单清晰,但是反而部署上一个适合计算机运算