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

    方案一:找规律,时间复杂度为O(1).

        public int bulbSwitch(int n) {
            return (int)Math.sqrt(n);
        }

    方案二:笨法子,按题目叙述逐行实现,时间复杂度为O(N2),系统超时.

        public int bulbSwitch(int n) {
            int[] arrBulbStatus = new int[n];
            for (int i = 1; i <= n; i++) { // on the i round
                for (int j = i-1; j < arrBulbStatus.length; j += i) { // toggle every i bulb
                    if (arrBulbStatus[j] == 1) {
                        arrBulbStatus[j] = 0;
                    } else {
                        arrBulbStatus[j] = 1;
                    }
                }
            }
            int res = 0;
            for (int i = 0; i < arrBulbStatus.length; i++) { // count how many bulbs are on.
                if (arrBulbStatus[i] == 1) {
                    res++;
                }
            }
            return res;
        }
  • 相关阅读:
    理解numpy.dot()
    Numpy数组操作
    numpy.rollaxis函数
    数组的分割
    数组的组合
    轴的概念
    Numpy数组解惑
    Django2.1.3 urls.py path模块配置
    ubuntu18.04创建虚拟环境时提示bash: /usr/local/bin/virtualenvwrapper.sh: 没有那个文件或目录 的解决办法
    对银行卡号进行验证(转)
  • 原文地址:https://www.cnblogs.com/lasclocker/p/5154118.html
Copyright © 2011-2022 走看看