Description

設計一個停車場系統,有三種車位:大 (1)、中 (2)、小 (3),分別有固定數量。addCar(carType) 嘗試停入對應車位,成功回傳 true,車位已滿回傳 false。

Example:

Input: [“ParkingSystem”,“addCar”,“addCar”,“addCar”,“addCar”] > [[1,1,0],[1],[2],[3],[1]] Output: [null,true,true,false,false]

Intuition#

核心思路:用陣列或變數記錄各種車位的剩餘數量,addCar 時檢查並扣減。

  • 直接模擬即可,沒有複雜邏輯
  • 三個計數器分別追蹤大、中、小車位的剩餘量

Approaches#

1: Three Variables#

  • 概念: 用三個變數記錄各車位剩餘數量
  • 時間複雜度: O(1) - 每次操作
  • 空間複雜度: O(1) - 固定變數
class ParkingSystem(big: Int, medium: Int, small: Int) {
    private var bigSlots = big
    private var mediumSlots = medium
    private var smallSlots = small

    fun addCar(carType: Int): Boolean {
        return when (carType) {
            1 -> if (bigSlots > 0) { bigSlots--; true } else false
            2 -> if (mediumSlots > 0) { mediumSlots--; true } else false
            3 -> if (smallSlots > 0) { smallSlots--; true } else false
            else -> false
        }
    }
}

⭐2: Array-Based#

  • 概念: 用陣列統一管理,carType 直接作為 index
  • 時間複雜度: O(1) - 每次操作
  • 空間複雜度: O(1) - 固定大小陣列
class ParkingSystem(big: Int, medium: Int, small: Int) {
    private val slots = intArrayOf(0, big, medium, small)  // index 0 不用

    fun addCar(carType: Int): Boolean {
        if (slots[carType] > 0) {
            slots[carType]--
            return true
        }
        return false
    }
}

用陣列的好處是消除 when/switch 分支,程式碼更簡潔。carType 直接對應 index 1、2、3,index 0 作為 padding 不使用。

🔑 Takeaways#

  • Pattern: 資源管理 / 容量計數 -> 計數器 / 陣列追蹤
  • 關鍵技巧: 將 type 映射到 array index 可以消除條件分支,程式碼更乾淨