LeetCode -- Bulb Switcher

来源:互联网 发布:使用另一个php的变量 编辑:程序博客网 时间:2024/06/05 18:36
题目描述:
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.


N个灯泡初始化为关闭。
有N个灯泡,遍历N轮,在第i轮中对每i个灯泡进行toggle操作。toggle:开->关;关->开。
分析:
N个灯泡中被操作偶数次的一定是关闭,奇数次的为开。
因此,对于数字N,遍历从[1,N]的每个数字,找出能够被整除奇数次的进行求和即可。


方案一:


public int BulbSwitch(int n){var sum = 0;for(var i = 1;i <= n; i++){var count = 0;for(var j = 1; j<= i ;j++){if(i % j == 0){count ++;}}if(count % 2 != 0){sum++;}}return sum;}



复杂度为N^2,当N=99999时直接超时。


方案二:
N=1,result=1 (1)
N=2,result=1 (1)
N=3,result=1 (1)
N=4,result=2 (1,4)
N=5,result=2 (1,4)
N=6,result=2 (1,4)
N=7,result=2 (1,4)
N=8,result=2 (1,4)
...
规律:
当N=K,解的个数为K中包含完全平方数的个数,分析:
对于数字X,假设X不为完全平方数,意味不存在K1*K2=X 且 K1=K2。则无论K为几,到最后总是关闭状态,因为K被操作的次数总为偶数次。
因此题目进一步转化为,求小于N的完全平方数的个数。


private List<int> cache = new List<int>();    public int BulbSwitch(int n) {        if(n == 0){            return 0;        }       int start = 0;    if(cache.Count > 0){    var len = cache.Count- 1;    for(var i = len;i>=0;i--){    if(cache[i]<n){    start = i;    }    }    }else{    cache.Add(1);    }        for(var i = start+1; 2*i + 1 + cache[i-1] <=n ;i++)    {    cache.Add(2*i + 1 + cache[i-1]);    }        return cache.Count();    }



解法三:直接返回N的平方根。
public int BulbSwitch(int n) {        return (int)Math.Sqrt(n);}



1 0
原创粉丝点击