zoukankan      html  css  js  c++  java
  • 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.


    用DP非常直观的解法如下,但是超时了。
    public int BulbSwitch(int n) {
            var dp = new bool[n+1];
            for(int i=1;i<=n;i++)
            {
                int j = 1;
                while(i*j<=n)
                {
                    dp[i*j] = !dp[i*j];
                    j++;
                }
            }
            int res=0;
            for(int i =1;i<=n;i++)
            {
                if(dp[i] == true) res++;
            }
            return res;
        }

    仔细分析,以6,16为例,6可以分解为[1,6],[2,3],[3,2],[6,1],也就是说,反复了四次,on/off不变,所以是off。只要能分解为偶数对个两个数的相乘,就是off。那什么情况下会有奇数个分解呢?只要在恰好是平方差数的时候,那么问题化简为求1-n这些数里哪些是平方差数。代码如下:

    public int BulbSwitch(int n) {
            int res=0;
            for(int i=1;i<=Math.Sqrt(n);i++)  if(i*i<=n) res++;
            return res;
        }

    更为简单的方法是只需要知道sqrt就好了。。

    public int BulbSwitch(int n) {
            return  (int)Math.Sqrt(n);
        }
  • 相关阅读:
    Mysql 使用触发器,把插入的数据在插入到宁一张表里
    Mysql 查询今天的某些时间之外的数据
    PHPStorm+XDEBUG 调试Laravel
    Python 2.7 爬取51job 全国java岗位
    Tp3.1 文件上传到七牛云
    TP3.1 一对多模型关联
    Mysql 主从配置
    自动化测试Java一:Selenium入门
    Selenium基于Python 进行 web 自动化测试
    Python 创建XML
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5902465.html
Copyright © 2011-2022 走看看