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);
            }

    这才是正确的姿势。

  • 相关阅读:
    python实现二分查找算法例子代码
    Python实现计算圆周率π的值到任意位的方法示例
    什么是TWS耳机
    [置顶] 单例模式lua实现
    推荐五星级C语言学习网站
    poj2689 Prime Distance 有难度 埃拉托斯尼斯筛法的运用
    局域网
    pager-taglib分页处理的使用
    创建ListView的基本步骤
    求最大连续子数列和(只扫描一次数列)
  • 原文地址:https://www.cnblogs.com/yh2015/p/7334607.html
Copyright © 2011-2022 走看看