[leetcode-319-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.

思路:

第一反应就是暴力 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

转载于:https://www.cnblogs.com/hellowooorld/p/7570918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值