最直观最容易想的方法,暴力破解方法:
class Solution {
public:
int bulbSwitch(int n) {
vector<int> state(n,0);
for(int i = 1;i <= n;i++)
{
for(int j = i-1;j < n;j += i)
{
state[j] ^= 1;
}
}
return count(state.begin(),state.end(),1);
}
};
执行结果:
Time Limit Exceeded
Details
Last executed input
10000000
最后几个用例超时(复杂度n的平方),说明程序需要优化,程序实现上没看到哪里可以再优化了,或许从数学角度可以进行优化。
看了下讨论区,果然只能是数学解法
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
运行效率:
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Bulb Switcher.
Memory Usage: 5.7 MB, less than 93.29% of C++ online submissions for Bulb Switcher.