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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值