LeetCode319——Bulb Switcher

LeetCode319——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.
Examples:

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.


题意

首先定义操作叫做switch:如果灯开着就关,如果关着就开。
第一次,从1开始以每次+1的方式迭代执行switch
第二次,从2开始以每次+2的方式迭代执行switch

第n次,对最后一个灯执行switch


我的思路

构建数组,按照题意只需要两重循环就能解决——最后超时,但是后来看了标准答案感觉自己的智商深深的被碾压了。
代码:

class Solution {
private:
    void change(vector<int>&nums,int j)
    {
        if (nums[j] == 0)
        {
            nums[j] = 1;
        }
        else
        {
            nums[j] = 0;
        }
    }
public:
    int bulbSwitch(int n) {
        vector<int>nums(n, 0);
        int count = 0;
        for (int i = 0; i < n; i++)//i+1 is operations
        {
            for (int j = i; j < n;j= j + i + 1)
            {
                change(nums,j);
            }
        }
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] == 1)
                count++;
        }
        return count;
    }
};

标准答案

One line XXX solution,这是Discuss区域的答案,原来是一道数学题,虽然感觉自己的智商确实被碾压,但是感觉其实很多解并没有说出详细原因,直到看到https://leetcode.com/discuss/75014/math-solution,给出的解释非常清楚:

A bulb ends up on iff it is switched an odd number of times.

Bulb i is switched in round d iff d divides i. So bulb i ends up on iff it has an odd number of >divisors.

Divisors come in pairs, like i=12 has divisors 1 and 12, 2 and 6, and 3 and 4. Except if i is a >square, like 36 has divisors 1 and 36, 2 and 18, 3 and 12, 4 and 9, and double divisor 6. So bulb >i ends up on iff and only if i is a square.

So just count the square numbers.

大概解释一下,当一个灯泡被执行偶数次switch操作时它是关着的,当被执行奇数次switch操作时它是开着的,那么这题就是要找出哪些编号的灯泡会被执行奇数次操作。

现在假如我们执行第 i 次操作,即从编号i开始对编号每次+i进行switch操作,对于这些灯来说,
如果其编号 jj=1,2,3,,n 能够整除i,则编号 j 的灯需要执switch操作。
具备这样性质的i是成对出现的,比如:
j=12 时,编号为12的灯,在第1次,第12次;第2次,第6次;第3次,第4次一定会被执行Switch操作,这样的话,编号为12的等肯定为灭。
但是当完全平方数36就不一样了,因为他有一个特殊的因数6,这样当 i=6 时,只能被执行一次Switch操作,这样推出,完全平方数一定是亮着的,所以本题的关键在于找完全平方数的个数。
代码:

class Solution {
public:
    int bulbSwitch(int n) {
        return sqrt(n);
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值