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

  • 相关阅读:
    Leetcode 217 存在重复
    Leetcode 125验证回文串
    HTML标签
    Having dreams is what makes life tolerable.
    Database数据库——MySQL简述
    Python实践之路8——选课系统
    Python学习之路16——线程、进程和协程
    Python实践之路7——计算器
    Python学习之路14——Socket
    Python学习之路13——异常处理
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5777943.html
Copyright © 2011-2022 走看看