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.
解法一:
代码:
public class Solution {
public int bulbSwitch(int n) {
int count = 0;
int result = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
if(i % j == 0){
count++;
}
}
if(count % 2 == 1){
result++;
}
}
return n >= 0 ? result : 0;
}
}此方法过于复杂,提交时会抛出异常Time Limit Exceeded
解法二:一般来说,约数都是成对出现的。约数是奇数的情况只有在平方数才出现。那么代码可以改进为
代码:
public class Solution {
public int bulbSwitch(int n) {
int result = 0;
for(int i = 1; i * i <= n; i++){
result++;
}
return (n >= 0 ? result : 0);
}
}上述代码有改进的空间,小于 n 的平方数的个数可以直接计算 n 的平方根得到:
代码:
public class Solution {
public int bulbSwitch(int n) {
return (int)(n >= 0 ? Math.sqrt(n) : 0);
}
}
开灯问题的优化算法
本文探讨了经典的开灯问题,给出了两种不同的解决方案。第一种方法通过遍历所有灯泡来确定最终有多少灯处于开启状态,但这种方法效率较低。第二种方法则通过数学规律简化问题,直接计算出结果。
901

被折叠的 条评论
为什么被折叠?



