zoukankan      html  css  js  c++  java
  • 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.

    题意:

    打开n个灯泡;

    第i轮,每第i个灯泡反转;(2<=i<=n)

    求最后亮的灯泡数目;

    思路:

    常规超时;

    规律:

    n:  1  2  3  4  5  6  7  8  9  10  11

    ans: 1  1  1  2  2  2  2  2  3  3  3

    1 class Solution {
    2 public:
    3     int bulbSwitch(int n) {
    4         return sqrt(n);
    5     }
    6 };
    View Code

     --------------更新----------------

    背后原理:

    第i轮反转时,i的倍数位置的灯泡状态反转;

    则对于灯泡i,每次到其因子时都会反转;

    而因子一般成对出现,两次反转后状态不变;

    唯一例外是两因子相同,则只会反转一次;

    此时,该数为平方数;

    则对于n来说,实际是求有多少个平方数;

    故sqrt(n)。

  • 相关阅读:
    DevCon 5 2019 活动照片
    区块链小册 | 必知的运营常识
    区块链小册 | 必知的运营渠道
    产品经理需求沟通的艺术
    作为产品经理要如何面对失败?
    展示亚洲金融科技状况的 15 张金融科技地图
    成为区块链行业的产品经理是什么感觉
    腾讯产品经理能力模型
    jQuery 知识点大纲
    call()与apply()区别
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5777943.html
Copyright © 2011-2022 走看看