319. Bulb Switcher

本文针对LeetCode上的开关灯问题提供了解决方案,通过C++和Java两种语言实现,并提出了一种更高效的求解方法——直接对输入数值开方取整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  原文链接:http://blog.youkuaiyun.com/baidu_23318869/article/details/50386323

问题链接:https://leetcode.com/problems/bulb-switcher/


[cpp]  view plain  copy
  1. // CPP  
  2. class Solution {  
  3. public:  
  4.     int bulbSwitch(int n) {  
  5.         int result = 0;  
  6.         for (int i = 1; i * i <= n; ++i) {  
  7.             ++result;  
  8.         }  
  9.         return result;  
  10.     }  
  11. };  

[java]  view plain  copy
  1. // JAVA  
  2. public class Solution {  
  3.     public int bulbSwitch(int n) {  
  4.         int result = 0;  
  5.         for (int i = 1; i * i <= n; ++i, ++result)  
  6.             ;  
  7.         return result;  
  8.     }  
  9. }  

注:上述代码可以进一步优化成一步完成,即对n开平方并取整的结果

return Math.sqrt(n)

智商被碾压的前奏答案:(Time Limit Exceeded超时)

public class Solution {
    public int bulbSwitch(int n) {
        if(n == 1) return 1;
        
        int result = n;
        int[] state = new int[n+1];
        
        for(int i=1;i<=n;i++)
            state[i] = 1;
        
        for(int i=2;i<=n;i++) {
            for(int l=1;l<=n;l++) {        // 进一步优化为:for(int l=i;l<n,l+=i),可省去判断直接进行灯状态的反转

               if(l%i == 0)
                    state[l] = 1-state[l];
                    if(state[l] == 1) {
                        result += 1;
                    } else {
                        result -= 1;
                    }
            }
            
        }
        
        int res = 0;
        for(int k=1;k<=n;k++) {
            if(state[k] == 1) {
                res +=1;
            }
        }
        return res;
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值