LeetCode:Bulb Switcher

我的未来我决定 提交于 2020-05-04 10:15:26

1、题目名称

Bulb Switcher(灯泡开关)

2、题目地址

https://leetcode.com/problems/bulb-switcher/

3、题目内容

英文: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.

中文:现有n个灯泡,默认都是关闭的。第一轮会打开所有的灯泡,第二轮关闭所有偶数次序的灯泡,第三轮翻转所有次序为三的倍数位置的灯泡,直到第n轮拨动最后一个灯泡的开关。试确定第n轮后还有几盏灯是亮的。

4、解题方法1(TLE)

一开始我还是尝试着写了一段用于暴力破解问题的代码,这段代码毫无悬念地会导致TLE(Time Limit Exceeded)。

Java代码如下:

/**
 * 灯泡开关测试
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年1月7日 下午11:11:02
 */
public class Solution {
    public int bulbSwitch(int n) {
        if (n <= 0) {
            return 0;
        }
        boolean[] bulbs = new boolean[n];
        for (int i = 0; i < n; i++) {
            bulbs[i] = false;
        }
        for (int i = 0; i <= n / 2; i++) {
            for (int j = i; j < n; j = j + i + 1) {
                bulbs[j] = !bulbs[j];
            }
        }
        for (int i = n / 2 + 1; i < n; i++) {
            bulbs[i] = !bulbs[i];
        }
        int counter = 0;
        for (boolean bulb : bulbs) {
            if (bulb) {
                counter++;
            }
        }
        return counter;
    }
}

5、解题方法2

后来我发现有一种方法更为简单,返回值其实就是n开方后向下取整的得数。

下面我来解释一下。对于每个数字来说,除了平方数,都有偶数个因数。

如6有4个因数:1×6=6,2×3=6

如60有个因数:1×60=60,2×30=60,3×20=60,4×15=60,5×12=60,6×10=60

可以看出,非平方数的因数总是成对出现的,只有平方数的因数才是奇数,因为平方数除平方根外,其他的因数都是成对出现的!对于当前的开关灯泡问题,可知到最后处在平方数位置的灯泡一定是开启的,其他位置的灯泡一定是关闭的。而要计算一个数之下有多少小于或等于它的平方数,使用一个开平方用的函数就可以了。

解题Java代码如下:

/**
 * 灯泡开关测试
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年1月7日 下午11:11:02
 */
public class Solution {
    public int bulbSwitch(int n) {
        return (int) (n >= 0 ? Math.sqrt(n) : 0);
    }
}

END

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!