[Leetcode] 319. Bulb Switcher 解题报告

来源:互联网 发布:photoshop cs软件下载 编辑:程序博客网 时间:2024/06/08 05:43

题目

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.

思路

1、朴素解法:朴素解法比较简单,没有算法技巧,可惜过不了所有数据。

2、质因数法:仔细分析这道题目就会发现,在n遍循环中,改变第i个灯泡状态的只有i的因数(而不是质因数)。例如8,那么在1,2,4,8遍的时候状态就会改变;而对于9而言,在第1,3,9遍的时候会改变状态。发现规律了吗?就是对于非平方数而言,状态会被改变奇数次;对于平方数而言,状态只会被改变偶数次,因而最终灯一定是灭的。所以这道题目实际上只需要返回小于等于n的平方数的个数就可以了,数学的魅力很神奇有木有?

好消息是:据说FLAG现在已经不考这种类似于智力题的东西了,所以大家做着玩一玩就可以了^_^。

代码

1、朴素解法:

class Solution {public:    int bulbSwitch(int n) {        vector<bool> status(n, false);        for(int i = 1; i <= n; ++i) {            for (int j = i - 1; j < n; j += i) {                status[j] = !status[j];            }        }        int ret = 0;        for (int i = 0; i < n; ++i) {            if (status[i]) {                ++ret;            }        }        return ret;    }};

2、质因数法:

class Solution {public:    int bulbSwitch(int n) {        return sqrt(n);    }};

原创粉丝点击