LeetCode|Bulb Switcher

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 ith round, you toggle every i bulb. 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.

方法一:
先来个朴素版的

class Solution {
public:
    int bulbSwitch(int n) {
        vector<int> v(n, 0);
        for(int i = 1; i <= n; i++)
            for(int j = 0; j < n; j++)
                v[j] ^= 1;
        int cnt = 0;
        for(int j = 0; j < n; j++)
            if(v[j]) cnt++;
        return cnt;
    }
};

复杂度O(n^2),test case n = 99999 就挂了

所以这题是个数学题
方法二:
对于灯i来说,他 toggle的次数就等于他除了1以外因子的个数,见下例:
6 : {1, 2, 3, 6}
7 : {1, 7}
9:{1, 3, 9}
如果把第0次算上,第0次时所有的灯都是灭的。那么第一轮就是开所有的灯…此时灯i最后的状态就由它有多少个因子来决定了。比如6有4个,7有2两个,最后的状态就是off。9有三个因子,所以最后是on。所以可以得出所有的完全平方数都是奇数个因子,对应的灯最后就是on。所以此题可以转化为求[1, n]有多少个完全平方数。

class Solution {
public:
    int bulbSwitch(int n) {
        return sqrt(n);
    }
};

参考:
https://leetcode.com/discuss/91371/share-my-o-1-solution-with-explanation

解析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值