LeetCode 319. Bulb Switcher
Description
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Input: 3 Output: 1 Explanation: At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on, on, on]. After second round, the three bulbs are [on, off, on]. After third round, the three bulbs are [on, off, off]. So you should return 1, because there is only one bulb is on.
描述
初始時有 n 個燈泡關閉。 第 1 輪,你開啟所有的燈泡。 第 2 輪,每兩個燈泡你關閉一次。 第 3 輪,每三個燈泡切換一次開關(如果關閉則開啟,如果開啟則關閉)。第 i 輪,每 i 個燈泡切換一次開關。 對於第 n 輪,你只切換最後一個燈泡的開關。 找出 n 輪後有多少個亮著的燈泡。
示例:
輸入: 3 輸出: 1 解釋: 初始時, 燈泡狀態 [關閉, 關閉, 關閉]. 第一輪後, 燈泡狀態 [開啟, 開啟, 開啟]. 第二輪後, 燈泡狀態 [開啟, 關閉, 開啟]. 第三輪後, 燈泡狀態 [開啟, 關閉, 關閉]. 你應該返回 1,因為只有一個燈泡還亮著。
思路
- 數學題,對給定的數字開平方向下取整即是答案。
- 暴力求解(會超時),但是通過暴力解法可以發現規律。我們宣告一個長度為 n 的陣列,陣列初始值為 0 。然後我們按照題目要求對其進行改變狀態的操作,0 表示關,1 表示開。我們通過這個會發現如果給定的 n 為前三個數(1~3)會有 1 盞燈亮著,如果給定的 n 為接下來的 5 個數 (4~8),會有 2 盞燈亮著,接下來的 7 個數(9~15)會有3 盞燈兩者,我們稱給定的所有可能的 n 中,最後剩下相同的燈亮著的情況的 n 為一組,於是可以發現每組 n 的個數是一個首項為 3 公差為 2 的等差數列。
- 於是有了第一個解法:我們不斷的從 n 中減去,3,5,7 ... (n 小於零就停止),能減少多少次就有多少盞燈亮著。
- 我們可以發現 1~3:1;4~8:2;9~15:3,16~25:4,不難發現我們對 n 開放取整就可以得到答案,關於嚴格的數學證明請參考這裡 -solution-with-explanation) 。
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-02-23 18:46:36 # @Last Modified by:何睿 # @Last Modified time: 2019-02-23 19:46:07 class Solution: def bulbSwitch(self, n: int) -> int: return int(n**0.5) def bulbSwitch2(self, n: int) -> int: count, i = 0, 3 # 首項為3,公差為 2 的等差數列 # n 為這些數字的和 while n > 0: # 每次從 n 中去掉一項 n -= i i += 2 # 記錄去掉的次數 count += 1 # 次數就是剩下的晾著的燈泡個數 return count def bulbSwitch3(self, n: int) -> int: # 最直觀的思路,用一個數組表示燈泡的開關情況,0 表示關,1 表示開 # !!! 此方法會超時 bulbs = [0 for i in range(n)] for i in range(n): j = i # 每輪調整 i 整數倍的位置 while j < n: bulbs[j] ^= 1 j += i + 1 # 統計最後剩下的 1 的個數 return bulbs.count(1)
原始碼檔案在這裡 。