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 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.

题意就是,轮流开关灯泡,最简单就是直接遍历,但是肯定会超时,网上看到了一个做法,直接开根号,看到这个数学方法,才深知自己的智商再一次的被碾压了。

建议和leetcode 672. Bulb Switcher II 轮流开关灯泡 + 数学公式 一起学习

代码如下:

import java.util.Arrays;

/*
 * 本题的关键在于找完全平方数的个数。 
 * */
class Solution 
{
     public int bulbSwitch(int n) 
     {
         if(n<=0)
             return 0;
         else
             return (int)Math.sqrt((double)n);    
     }

    /*
     * 一般人都能想到的方法,但是会超时 
     * */
    public int bulbSwitchByBruteFource(int n) 
    {
        if(n<=0)
            return 0;
        boolean []bulb=new boolean[n];
        Arrays.fill(bulb, false);

        for(int i=0;i<n;i++)
        {
            for(int j=i;j<n;j=j+(1+i) )
            {
                bulb[j]=!bulb[j];
            }
        }

        int count=0;
        for(int i=0;i<n;i++)
        {
            if(bulb[i])
                count++;
        }
        return count;
    }
}

下面是C++的做法,就是轮流开开关,看到这么简单的做法,我也是震惊了,这道题的做法很棒,值得学习,

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>

using namespace std;


class Solution
{
public:
    int bulbSwitch(int n) 
    {
        if (n <= 0)
            return 0;
        else
            return (int)sqrt((double)n);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值