【做题也是一场游戏】1603. 设计停车系统

336 阅读1分钟

题目地址

leetcode-cn.com/problems/de…

题目描述

请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。

请你实现 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 <= 1000
carType 取值为 1 2  3
最多会调用 addCar 函数 1000 

题解

用三个属性记录当前的车位数,每次停车的时候进行判断

class ParkingSystem {

    private int big;

    private int medium;

    private int small;

    public ParkingSystem(int big, int medium, int small) {
        this.big = big;
        this.medium = medium;
        this.small = small;
    }
    
    public boolean addCar(int carType) {
        switch(carType){
            case 1:
                if (big >= 1) {
                    big--;
                    return true;
                }
                return false;
            case 2:
                if (medium >= 1) {
                    medium--;
                    return true;
                }
                return false;
            case 3:
                if (small >= 1) {
                    small--;
                    return true;
                }
                return false;
            default:
                return false;
        }
    }
}

时间复杂度

  • 时间复杂度:单次操作为 O(1)O(1)

  • 空间复杂度:O(1)O(1)

使用一个int分段记录

停车位最大 1000,而 1000 的二进制是 1111101000, 而 java 的int是32,正好可以放下三个

class ParkingSystem {

    int counts;

    public ParkingSystem(int big, int medium, int small) {
        counts = (small << 20) | (medium << 10) | big;
    }

    public boolean addCar(int carType) {
        int moveBitCount = ((carType - 1) * 10);
        if (((counts >> moveBitCount) & 0b1111111111) == 0){
            return false;
        } else {
            counts = counts - (1 << moveBitCount);
            return true;
        }
    }
}

时间复杂度

  • 时间复杂度:单次操作为 O(1)O(1)

  • 空间复杂度:O(1)O(1)