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.

這個題最原始想法如下,對每一個回合遍歷一次,n個回合後,輸出on的個數:

int bulbSwitch(int n) {
        
        vector<int> bulb(n,0);
        int round_b=1;
        for(;round_b<=n;round_b++){
            int i=0;
            while(i<n){
                i=i+round_b;
                if(i>n) break;
                bulb[i-1]==0?bulb[i-1]=1:bulb[i-1]=0;
            }
        }
        int ans=0;
        for(auto x :bulb){
            ans+=x;
        }
        return ans;
    }
很明顯會超時,因爲窮舉法肯定不是出題人想要的,我仔細研究了一下發現了以下規律:輸出爲0       n: 0 ;輸出爲1       n: 1,2,3 ;輸出爲2       n: 4,5,6,7,8   ;輸出爲3       n: 9,10,11,12,13,14,15。很明顯是1,3,5,7...的規律,所以對於一個n,只需要找到n在第幾行就行,代碼如下:

int bulbSwitch(int n) {
        /*
        vector<int> bulb(n,0);
        int round_b=1;
        for(;round_b<=n;round_b++){
            int i=0;
            while(i<n){
                i=i+round_b;
                if(i>n) break;
                bulb[i-1]==0?bulb[i-1]=1:bulb[i-1]=0;
            }
        }
        int ans=0;
        for(auto x :bulb){
            ans+=x;
        }
        return ans;*/
        return sqrt(n);
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章