-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmove-zero.go
57 lines (53 loc) · 992 Bytes
/
move-zero.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
55
56
57
package array
// https://leetcode-cn.com/problems/move-zeroes/
// The problem is more like the gc algorithm,
// implement by swap
func moveZeroes(nums []int) {
i := 0
j := 0
for {
// i find first zero
for ; i < len(nums) && nums[i] != 0; i++ {
}
// reach the end
if i == len(nums) {
return
}
// if not reach the end, j find the first non-zero from i+1 or j+1
// for j = i+1; j < len(nums) && nums[j] == 0; j++ {
for j = max(i+1, j+1); j < len(nums) && nums[j] == 0; j++ {
}
if j == len(nums) {
for i < len(nums) {
nums[i] = 0
i++
}
} else {
nums[i] = nums[j]
nums[j] = 0
}
}
}
// implement by copy algorithm, more like gc algorithm
// better and simple answer
func moveZeroes2(nums []int) {
j := 0
for i := 0; i < len(nums); i++ {
if nums[i] != 0 {
nums[j] = nums[i]
j++
}
}
// DO NOT FORGET THIS
for j < len(nums) {
nums[j] = 0
j++
}
}
func max(a int, b int) int {
if a < b {
return b
} else {
return a
}
}