-
Notifications
You must be signed in to change notification settings - Fork 1
/
bulb.go
54 lines (51 loc) · 830 Bytes
/
bulb.go
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
50
51
52
53
54
package bulb
func minFlips(target string) int {
return useGreedy(target)
}
// useBruteForce time complexity O(N), space complexity O(1)
func useGreedy(target string) int {
var ans int
n := len(target)
if n < 1 {
return ans
}
var first int
for {
for ; first < n; first++ {
if target[first] == '0' {
continue
}
ans++
break
}
first++
if first >= n {
break
}
for ; first < n; first++ {
if target[first] == '1' {
continue
}
ans++
break
}
}
return ans
}
// simple is a simpler approach for useGreedy, just use one loop.
// time complexity O(N), space complexity O(1)
func simple(target string) int {
var ans int
start := '0'
for _, c := range target {
if c != start {
ans++
if start == '0' {
start = '1'
} else {
start = '0'
}
}
}
return ans
}