您的位置:首页 > 其它

leetcode 319 Bulb Switcher

2015-12-21 23:54 471 查看

题目描述

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.

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.

按照题目描述,假设共有i轮循环,每次只要将第i*n个元素状态改变即可,利用二重循环即可实现。

java实现代码如下:

public class solution {
static int o;
static int[] blub;
static int bulbSwitch(int n){
o=n;
blub =new int [n+1];
for(int m=0;m<=n;m++){
blub[m]=1;
}

for(int i=2;i<n;i++){
change(i);
}
int count = 0;
blub
=blub
*-1;
for(int m=1;m<=n;m++){
if(blub[m]==1)
count++;
}
System.out.println(count);
return count ;
}
static void change(int x){
for(int i=1;i<=o/x;i++){
blub[i*x]=blub[i*x]*-1;
}
}
}


解题思路

实验了几个简单的例子发现通过,然而提交之后超时。。。 查看Discuss发现原来是一个数学问题

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

Bulb i is switched in round d iff d divides i. So bulb i ends up on iff 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 if 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 iff and only if i is a square.

So just count the square numbers.

奇数次操作之后,灯的状态为关,偶数次操作后灯为关。

在已给定n的情况下,考虑各轮操作的执行过程。

当进行第 i 轮操作时,第 j 个灯是否变更状态取决于 j 能否被 i 整除,而一般情况下,这样的 i 是成对出现的,如12的约数为(1,12);(2,6);(3,4);即12号灯在第1,2,3,4,6,12轮操作时均改变状态。共偶数次操作所以此时灯的状态为关闭。

在特殊情况下,若数字j存在完全平方根,那么该数的约数个数就不为偶数,而是奇数。那么操作结束求后亮灯个数的问题就转化为了求序列N中完全平方数的个数的问题。也即相当于对序列N开方。

正确答案

public int bulbSwitch(int n) {
return (int)Math.sqrt(n);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode