原文链接:http://blog.youkuaiyun.com/baidu_23318869/article/details/50386323
问题链接:https://leetcode.com/problems/bulb-switcher/
注:上述代码可以进一步优化成一步完成,即对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;
}
}