[LeetCode] Design Parking System

준규·2022년 12월 7일
0

1.문제



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 1, 2, or 3
  • At most 1000 calls will be made to addCar

2.풀이

  1. constructor 에서 객체를 생성해서 1 : big , 2 : medium, 3 : small 로 키 밸류 값을 할당해준다.
  2. 각 객체에서 map[carType] 값을 1 감소시킨다음 그 값이 0 보다 크다면 true, 아니라면 false를 리턴해준다.

/**
 * @param {number} big
 * @param {number} medium
 * @param {number} small
 */
const ParkingSystem = function (big, medium, small) {
  this.map = {};
  this.map[1] = big;
  this.map[2] = medium;
  this.map[3] = small;
};

/**
 * @param {number} carType
 * @return {boolean}
 */
ParkingSystem.prototype.addCar = function (carType) {
  if (this.map[carType + ""]-- > 0) { // 주어지는 carType 의 value - 1 값이 0 보다 크면 true
    return true;
  } else { // 아니라면 false
    return false;
  }
};


/** 
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new ParkingSystem(big, medium, small)
 * var param_1 = obj.addCar(carType)
 */

3.결과

profile
안녕하세요 :)

0개의 댓글