[leetcode] Bulb Switcher

题目:

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 nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

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.

方案一:找规律,时间复杂度为O(1).

    public int bulbSwitch(int n) {
        return (int)Math.sqrt(n);
    }

方案二:笨法子,按题目叙述逐行实现,时间复杂度为O(N2),系统超时.

    public int bulbSwitch(int n) {
        int[] arrBulbStatus = new int[n];
        for (int i = 1; i <= n; i++) { // on the i round
            for (int j = i-1; j < arrBulbStatus.length; j += i) { // toggle every i bulb
                if (arrBulbStatus[j] == 1) {
                    arrBulbStatus[j] = 0;
                } else {
                    arrBulbStatus[j] = 1;
                }
            }
        }
        int res = 0;
        for (int i = 0; i < arrBulbStatus.length; i++) { // count how many bulbs are on.
            if (arrBulbStatus[i] == 1) {
                res++;
            }
        }
        return res;
    }
原文地址:https://www.cnblogs.com/lasclocker/p/5154118.html