leetcode 319 Bulb Switcher


题目描述

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[n]=blub[n]*-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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值