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;
        }
  • 相关阅读:
    [ APIO 2015 ] 雅加达的摩天楼
    「POI2011 R1」Conspiracy
    「COCI2016/2017 Contest #2」Bruza
    「THUWC 2017」随机二分图
    「HAOI2015」按位或
    Topcoder Srm 726 Div1 Hard
    「LOJ6482」LJJ爱数数
    「2017 山东一轮集训 Day4」基因
    「Codechef April Lunchtime 2015」Palindromeness
    「UOJ207」共价大爷游长沙
  • 原文地址:https://www.cnblogs.com/lasclocker/p/5154118.html
Copyright © 2011-2022 走看看