319. Bulb Switcher

来源:互联网 发布:手机怎么破解网络限制 编辑:程序博客网 时间:2024/06/07 22:57

1、来源:点击打开链接

2、

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.
3、暴力破解又超时,心里苦(java):

public class Solution {    public int bulbSwitch(int n) {        int[] count=new int[n];        int i,j,sum=0;        for(i=0;i<n;i++)            count[i]=0;        for(i=0;i<n;i++){            j=i;            while(j<n){                count[j]=count[j]==0?1:0;                j+=(i+1);            }        }        for(i=0;i<n;i++)            sum+=count[i];        return sum;    }}
4、列出很多例子,可以发现规律(c++),虽然不是从“on,off的切换得出”,也不知道为什么,但出产自己还是很爽的:

class Solution {public:    int bulbSwitch(int n) {        return sqrt(n);    }};
5、在discuss区中有解释https://discuss.leetcode.com/topic/31929/math-solution/34:

A bulb ends up on iff it is switched an odd number of times.

Call them bulb 1 to bulb n. Bulb i is switched in round d if and only if d divides i. So bulb i ends up on if and only if it has an odd number of divisors.

Divisors come in pairs, like i=12 has divisors 1 and 12, 2 and 6, and 3 and 4. Except when i is a square, like 36 has divisors 1 and 36, 2 and 18, 3 and 12, 4 and 9, and double divisor 6. So bulb i ends up on if and only if i is a square.

表达的意思是:如果一盏灯最终是亮的话,则它被点击的次数为奇;

例如当n=10时,我们分别计算一些灯的on,off情况,

第1盏亮

第2盏不亮:2=2*1,意为把2分解2和1,,只有第1,2次要转换;

第3盏不亮:3=3*1,意为把3分解3和1,,只有第1,3次要转换;

第5盏不亮:5=5*1,意为把5分解3和1,,只有第1,5次要转换;

第6盏不亮:6=6*1或6=3*2,只有第1,2,3,6次要转换;

。。。。。。

从上面可以看出来,如果不是完全平方数分解,必定都是偶数次转换。而如9=9*1或9=3*3,则是偶数次转换;

0 0
原创粉丝点击