-
Notifications
You must be signed in to change notification settings - Fork 0
/
BulbSwitcher.java
49 lines (45 loc) · 1.27 KB
/
BulbSwitcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class BulbSwitcher{
// time limit exceed haha
public int bulbSwitch(int n) {
boolean[] state = new boolean[n+1];
for(int i = 1; i <= n; i++){
for(int j = i; j <= n; j += i){
state[j] = !state[j];
}
}
int count = 0;
for(int i = 1; i <= n; i ++){
if(state[i])
count ++;
}
return count;
}
// math magic!
// the result is the number of integer (1 - n) which has odd factors
// which is number of integers what are squares
// because factors come in pairs
// sqrt is O(lgn)
public int bulbSwitch(int n){
return (int) Math.sqrt(n);
}
// binary search
public int bulbSwitch(int n){
if(n < 2)
return n;
long start = 1, end = n / 2;
while(start < end){
long mid = start + (end - start + 1) / 2;
if(mid * mid <= n)
start = mid;
else
end = mid - 1;
}
return (int)start;
}
// O(1) solution
// just use power and log to calculate sqrt
// power and log in java is O(1)
public int bulbSwitch(int n){
return (int) Math.pow(2, 0.5 * (Math.log(n)/Math.log(2)));
}
}