Bulb Switcher
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 ith round, you toggle every i bulb. 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.
方法一:
先来个朴素版的
class Solution {
public:
int bulbSwitch(int n) {
vector<int> v(n, 0);
for(int i = 1; i <= n; i++)
for(int j = 0; j < n; j++)
v[j] ^= 1;
int cnt = 0;
for(int j = 0; j < n; j++)
if(v[j]) cnt++;
return cnt;
}
};
复杂度O(n^2),test case n = 99999 就挂了
所以这题是个数学题
方法二:
对于灯i来说,他 toggle的次数就等于他除了1以外因子的个数,见下例:
6 : {1, 2, 3, 6}
7 : {1, 7}
9:{1, 3, 9}
如果把第0次算上,第0次时所有的灯都是灭的。那么第一轮就是开所有的灯…此时灯i最后的状态就由它有多少个因子来决定了。比如6有4个,7有2两个,最后的状态就是off。9有三个因子,所以最后是on。所以可以得出所有的完全平方数都是奇数个因子,对应的灯最后就是on。所以此题可以转化为求[1, n]有多少个完全平方数。
class Solution {
public:
int bulbSwitch(int n) {
return sqrt(n);
}
};
参考:
https://leetcode.com/discuss/91371/share-my-o-1-solution-with-explanation