LeetCode (1603) - Design parking system

table of Contents

topic

1603. Design parking system
Please design a parking system for a parking lot. There are three different sizes of parking spaces in the parking lot: large, medium and small. Each size has a fixed number of parking spaces.

Please implement the ParkingSystem class:

ParkingSystem(int big, int medium, int small) Initialize the ParkingSystem class. The three parameters correspond to the number of parking spaces of each type.
bool addCar(int carType) Check if there is a parking space corresponding to carType. There are three types of carType: large, medium, and small, which are represented by numbers 1, 2 and 3 respectively. A car can only be parked in a parking space of the size corresponding to the carType. If there is no empty parking space, please return false, otherwise park the car in the parking space and return true.

Example 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 ,因为没有空的大车位,唯一一个大车位已经被占据了

prompt:

0 <= big, medium, small <= 1000
carType 取值为 1, 2 或 3
最多会调用 addCar 函数 1000 次

Problem solution (Java)

In this question, I used the switch statement and return!(big <= -1);replaced the if-else statement with

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:
                big--;
                return !(big <= -1);
            //放入的是中车位
            case 2:
                medium--;
                return !(medium <= -1);
            //放入的是小车位
            case 3:
                small--;
                return !(small <= -1);
        }
        return false;
    }
}
/**
 * Your ParkingSystem object will be instantiated and called as such:
 * ParkingSystem obj = new ParkingSystem(big, medium, small);
 * boolean param_1 = obj.addCar(carType);
 */

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114191157