zoukankan      html  css  js  c++  java
  • Bulb Switcher

    2017年8月9日 23:03:14

    Description:

    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.

    大概是这个意思:

    2015盏灯,一开始全部熄灭,序号分别是1-2015,先把1的倍数序号的灯的开关全部按一次,然后把2的倍数的灯的开关全部按一次,然后把3的倍数的开关按一次,以此类推,最后把2015的倍数灯的开关按一次。问最后亮着的灯有多少盏?

    下面是我的解题代码:

    static int GetResult(int n)
            {
                int[] lights = new int[n];
                for (int i = 1; i <= n; i++)
                {
                    for (int j = 1; j <= n; j++)
                    {
                        if (j % i == 0 && i % 2 != 0)
                        {
                            lights[j - 1] = lights[j - 1] == 0 ? 1 : 0;
                        }
                        else if (j % i == 0 && i % 2 == 0)
                        {
                            lights[j - 1] = lights[j - 1] == 1 ? 0 : 1;
                        }
                    }
                }
                int num = 0;
                for (int i = 0; i < n; i++)
                {
                    if (lights[i] == 1)
                        num += 1;
                }
                return num;
            }

    程序在测试的时候是没有什么问题的,但是在提交到LeetCode的时候提示失败,测试数字为99999;

    因为程序的时间复杂度是O(n^2),所以当数字为99999的时候获取结果时间过长。

    后来看了一下别人的解题思路:求1-2015中约数个数为奇数个的数!而只有平方数才有奇数个约数。

    1 2 3 4 5 6 ... 43 44 45
    1^2 2^2 3^2 4^2 5^2 6^2 ... 43^2 44^2 45^2
    2 4 9 16 25 36 ... 1849 1936 2025

    从上表可以看出n中有根号n个平方数,所以:

    static int GetResult(int n)
            {
                return (int)Math.Sqrt(n);
            }

    这才是正确的姿势。

  • 相关阅读:
    tomcat shutdown后,进程还存在linux系统中的解决办法
    nginx反向代理tcp协议的80端口
    redis集群搭建中遇到的一些问题
    《将博客搬至CSDN》
    最短路路径(1.1版待更新)
    线段树
    SDUT 3341 数据结构实验之二叉树二:遍历二叉树
    二叉树的遍历
    爆头题HDU
    图的入度和出度以及图的新的存储形式
  • 原文地址:https://www.cnblogs.com/yh2015/p/7334607.html
Copyright © 2011-2022 走看看