关闭

leetcode 319 Bulb Switcher

140人阅读 评论(0) 收藏 举报
分类:

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;
	}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:10998次
    • 积分:471
    • 等级:
    • 排名:千里之外
    • 原创:37篇
    • 转载:11篇
    • 译文:0篇
    • 评论:2条