問題:數組
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.spa
Example:three
Given n = 3. 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.
解決:it
【題意】這道題給了咱們n個燈泡,第一次打開全部的燈泡,第二次每兩個更改燈泡的狀態,第三次每三個更改燈泡的狀態,以此類推,第n次每n個更改燈泡的狀態。讓咱們求n次後,全部亮的燈泡的個數。io
例如:只有5個燈泡的狀況,'X'表示滅,‘√’表示亮,以下所示:ast
初始狀態: X X X X Xclass
第一次: √ √ √ √ √循環
第二次: √ X √ X √時間
第三次: √ X X X √lbs
第四次: √ X X √ √
第五次: √ X X √ X
① 直接解決,使用一個數組記錄每一個位置上燈泡的狀態,每次循環更改這些狀態。時間複雜度爲O(N^2)。超時。
② 找規律。計算亮的燈泡的個數,能夠找到以下規律:
共有1 ~ 3個燈泡:最終亮的燈泡個數 1
共有4 ~ 8個燈泡:最終亮的燈泡個數 2
共有9 ~ 15個燈泡:最終亮的燈泡個數 3
共有16 ~ 24個燈泡:最終亮的燈泡個數 4
共有25 ~ 35個燈泡:最終亮的燈泡個數 5
......
因此,有n個燈泡時,只須要找到一個最大的徹底平方數的值小於等於該數便可。
class Solution {//0ms public int bulbSwitch(int n) { int res = (int)Math.sqrt(n); return res; } }