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);
        }
  • 相关阅读:
    如何下载网络图片资源
    经典排序之快速排序(含红黑树)
    经典排序之归并排序
    node微信公众号开发---自动回复
    koa2的文件上传
    async await的用法
    Generator yield语法和 co模块
    CentOS 7 下安装 Nginx
    windows下nginx的安装及使用方法入门
    linux下nodejs安装以及如何更新到最新的版本
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5902465.html
Copyright © 2011-2022 走看看