leetcode 319 Bulb Switcher

1 暴力解法(超時):

 

package leetcode;

public class Solution319 {
	public int bulbSwitch(int n) {
        if(n == 0){
            return 0;
        }
        boolean[] bulbs = new boolean[n];
        int count = 1;
        int numOfbulbs = 0;
        while(count <= n) {
            for(int i = count-1; i < n; i+=count) {
                if(bulbs[i]) {
                    bulbs[i] = false;
                }else{
                    bulbs[i] = true;
                }
            }
            ++count;
        }
        
        StringBuffer s = new StringBuffer(new String(""));  
        for(int i = 0;i < n; ++i){
            if(bulbs[i]){
                ++ numOfbulbs;
            }
            s.append(bulbs[i] ? 1 : 0);
        }
        System.out.println(s);
        return numOfbulbs;
    }
	
	public static void main(String[] args) {
		Solution319 solution319 = new Solution319();
		int n = 30;
		for(int l = 0;l < 30; ++l) {
			solution319.bulbSwitch(l);
		}
	}
}
2 找規律解法:

 打印輸出出規律,然後再看具體的情況。

 code:

 

public class Solution319Lcq {
	public int bulbSwitch(int n) {
		if(n <= 3){
			return 1;
		}
		int wheel = 2;  
		int result = 0;
		int trackvehicle = 0;
		boolean isNotWheel = true;
		while(trackvehicle <= n){
			if(isNotWheel) {
				trackvehicle += 1;
				result += 1;
				//wheel;
				isNotWheel = !isNotWheel;
			}else{
				trackvehicle += wheel;
				wheel += 2;
				isNotWheel = !isNotWheel;
			}
		}
		return result;
	}
}

發佈了39 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章