[LeetCode] 1603. Design Parking System 문제 풀이

Kaite.Kang·2023년 5월 29일

알고리즘

목록 보기
1/1

문제

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

Implement the ParkingSystem class:

  • ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.
  • bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 12, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.

Example 1:

Input
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
[[1, 1, 0], [1], [2], [3], [1]]
Output
[null, true, true, false, false]

Explanation
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.

Constraints:

  • 0 <= big, medium, small <= 1000
  • carType is 12, or 3
  • At most 1000 calls will be made to addCar

풀이

class ParkingSystem(object):
    def __init__(self, big, medium, small):
        self.carTypes = {}

        self.carTypes[1] = big
        self.carTypes[2] = medium
        self.carTypes[3] = small

    def addCar(self, carType):
        if self.carTypes[carType] > 0:
            self.carTypes[carType] = self.carTypes[carType] - 1
            return True
        else:
            return False

배운 것

1. 파이썬 메소드는 첫번째 인수로 무조건 self를 받는다.

  • what?
    self는 객체 인스턴스자기자신을 참조하는 매개 변수이다.
    메소드에서 첫번째 인자로 파이썬에서 self를 자동으로 넘겨준다. 아무 인자를 추가하지 않아도 self는 넘겨준다.
    파이썬은 클래스의 메소드를 정의할 때 self를 명시하며, 이걸 메소드에 안보이게 전달하지만, 메소드를 불러올 때 self는 자동으로 전달된다. 

  • how?
    self를 사용함으로 클래스 내에 정의한 멤버에 접근할 수 있게된다.

2. 딕셔너리 활용하기

  • what?
    딕셔너리는 key:value로 매칭해서 값을 저장한다.

  • how?
    특정 Key 값을 찾아야할 때는 리스트보다 딕셔너리가 유용하다.

  • 배열, 튜플, 딕셔너리 선언 방법
    배열, 튜플, 딕셔너리 선언 방법을 비교해서 알아두자.

  배열[Array] 튜플(Tuple) 딕셔너리{Dictionary}
 선언 arr = [] tup = () dic = {}
 초기화 arr = [1, 2, 3, 4] tup = (1, 2, 3, 4) dic = {"january":1, "February": 2, "March":3 }
 불러오기 arr[0] tup[0] dic["March"]
  • 딕셔너리 문법
    딕셔너리 값 추가하는 방법과 삭제하는 방법을 알아두자.
# 삽입 방법1
>>> a = {1: 'a'}

# 삽입 방법2
>>> a[2] = 'b'
>>> a
{1: 'a', 2: 'b'}

# 리스트도 value로 추가 가능
>>> a['name'] = [1,2,3]
>>> a
{1: 'a', 2: 'b', 'name': [1, 2, 3]}

# 삭제
>>> del a[1]
>>> a
{2: 'b', 'name': [1, 2, 3]}

참고

0개의 댓글