Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

귤귤나무 일지

LeetCode - 1603. Design Parking System 본문

Programming/Coding Problems

LeetCode - 1603. Design Parking System

귤귤나무 2024. 11. 11. 19:52

보고 딱 떠오른 생각은 big, medium, small이 차례로 1, 2, 3이니까, 또 해시맵 사용해서 그에 대응하는 값을 1씩 줄이는 걸로 해야겠다.

class ParkingSystem {
private:
    int b = 0;
    int m = 0;
    int s = 0;
public:
    ParkingSystem(int big, int medium, int small) {
        b = big;
        m = medium;
        s = small;
    }
    
    bool addCar(int carType) {
        switch (carType) {
            case 1:
                if (b > 0) {
                    b--;
                    return true;
                }
                break;
            case 2:
                if (m > 0) {
                    --m;
                    return true;
                }
                break;
            case 3:
                if (s > 0) {
                    --s;
                    return true;
                }
        }
        return false;
    }
};

그리고 해설을 보니까 해시맵 말고 배열로 구현해도 되는 거였다.

 

class ParkingSystem {
private:
    vector<int> slot;
public:
    ParkingSystem(int big, int medium, int small) {
        slot = vector<int> {big, medium, small};
    }
    
    bool addCar(int carType) {
        if (slot[carType - 1] > 0) {
            slot[carType - 1]--;
            return true;
        }
        return false;
    }
};

 

해설에 있는 또다른 신박한 방법

class ParkingSystem {
private:
    vector<int> slot;
public:
    ParkingSystem(int big, int medium, int small) {
        slot = vector<int> {big, medium, small};
    }
    
    bool addCar(int carType) {
        return slot[carType - 1]-- > 0;
    }
};

 

KeyIdea

딱히 없음