首页 > 技术文章 > [leetcode-319-Bulb Switcher]

hellowooorld 2017-09-21 20:35 原文

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.

思路:

第一反应就是暴力 O(n2)的复杂度。

稍微仔细想了一下,对于第i个灯来说,是否亮只与他的因子个数相关,比如6,因子为1 2 3 6,那么最终6号等将是灭的,如果是9的话

因子为1 3 9,最终为亮的。也就是说因子个数为偶数个那么将是灭的。统计所有数的因子个数即可,时间复杂度也是O(n2).

经测试。。超时。。

int factorNum(int n)
{
    int fac = 0;
    for (int i = 2; i*i <= n; i++)
    {
        if (n%i == 0)
        {
            if (i*i == n)fac += 1;
            else fac += 2;
        }
    }
    fac += 1;
    return fac;
}
int bulbSwitch(int n)
{
    if (n <= 1)return 0;
    if (n == 2 || n == 3)return 1;
    int ret = 0;
    for (int i = 4; i <= n;i++)
    {
        if (factorNum(i) % 2 == 0)ret++;
    }
    return ret;
}

 

参考了大牛给的解法:

Explanation:
A light will be toggled only during the round of its factors, e.g. number 6 light will be toggled at 1,2,3,6 and light 12 will be toggled at 1,2,3,4,6,12. The final state of a light is on and off only depends on if the number of its factor is odd or even. If odd, the light is on and if even the light is off. The number of one number's factor is odd if and only if it is a perfect square!
So we will only need to loop to find all the perfect squares that are smaller than n!

就是求小于n的完全平方数的个数,因为只有像 1 4 9 16 25这些数字最后灯是亮的。

int bulbSwitch(int n) {
    int counts = 0;
    
    for (int i=1; i*i<=n; ++i) {
        ++ counts;    
    }
    
    return counts;
}

参考:

https://discuss.leetcode.com/topic/32301/my-0-ms-c-solution-with-explanation

推荐阅读