↓快轉到主要內容
  1. LeetCode/

LeetCode 3842: Toggle Light Bulbs

·1 分鐘· ·
LeetCode Easy Hash-Table Simulation Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-02-16

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

每出現一次就切換一次,所以最後亮著的是出現奇數次的燈泡。用集合模擬:在集合裡就拿掉,不在就加進去(Hash Table 模板一)。題目要由小到大回傳。

我的嘗試
#

第一版回傳 list(light),集合沒有順序。例如 [8, 1]:答案是 [1, 8],這版回傳 [8, 1]。加上 sorted 就 AC 了。

正確解法
#

class Solution:
    def toggleLightBulbs(self, bulbs: List[int]) -> List[int]:
        on = set()
        for b in bulbs:
            on ^= {b}                      # 在就拿掉,不在就加入
        return sorted(on)

複雜度
#

時間 O(n + k log k),k 是最後亮著的數量,空間 O(k)。

要特別避免的錯誤
#

  • 集合轉 list 不保證順序,題目要排序就要自己排。

面試口說整理
#

每次出現都切換,所以最後亮著的是出現奇數次的燈泡。我用集合做對稱差來切換,最後排序回傳。時間 O(n log n)。

相關文章

LeetCode 3679: Minimum Discards to Balance Inventory
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table Simulation Counting Array
LeetCode 3679 解題筆記:規則已經決定哪些要丟,直接模擬;長度 w 的視窗只計算「留下來」的到貨,被丟掉的離開視窗時不能再扣
LeetCode 2094: Finding 3-Digit Even Numbers
·1 分鐘
LeetCode Easy Hash-Table Enumeration Array
LeetCode 2094 解題筆記:反過來枚舉 100 到 998 的偶數,檢查需要的每個數字次數夠不夠;Counter 相減只留正數
LeetCode 3487: Maximum Unique Subarray Sum After Deletion
·1 分鐘
LeetCode Easy Greedy Hash-Table Array
LeetCode 3487 解題筆記:可以任意刪除,所以等於挑不重複的值;非負的全拿,全是負數時只拿最大的一個
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 分鐘
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 解題筆記:每次操作會讓最小的正數那一群變成 0,所以次數就是不同的正數有幾種
LeetCode 1646: Get Maximum in Generated Array
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 1646 解題筆記:照規則生成陣列:偶數位置 nums[i // 2],奇數位置 nums[i // 2] + nums[i // 2 + 1],n = 0 要特別處理