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)。

  • 相关阅读:
    避开unity的坑(转摘)
    独立游戏开发者创建工作室必看建议(转摘)
    程序员常去的网站
    使用Unity3D的50个技巧
    day 51 html 学习 js 学习
    day 50 Java Script 学习
    day 49 html 学习 css 学习
    day 47 html 学习 css 学习
    day 46 html 学习 列 表格,
    day45 html 初识,常见命令
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5777943.html
Copyright © 2011-2022 走看看