题目
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
解题思路
在原数组中剔除0值,append到一个新建的数组zeroSlice中,最终将zeroSlice append到剔除0值的nums数组中
记得遍历nums时,每找到一个0值并剔除后,index和nums的长度都要减1
代码
moveZeros.go
package _283_Move_Zeroes
func MoveZeroes(nums []int) {
length := len(nums)
var zeroSlice []int
for i := 0; i < length; i++ {
if 0 == nums[i] {
zeroSlice = append(zeroSlice, 0)
nums = append(nums[0:i], nums[i+1:]...)
i--
length--
}
}
nums = append(nums, zeroSlice...)
}
测试
moveZeros_test.go
package _283_Move_Zeroes
import "testing"
func SliceEqual(a, b []int) bool{
lena := len(a)
lenb := len(b)
if lena != lenb {
return false
}
for i := 0; i < lena; i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func TestMoveZeroes(t *testing.T) {
var tests = []struct{
input []int
output []int
}{
{[]int{0, 1, 0, 3, 12},
[]int{1, 3, 12, 0, 0}},
}
for _, test := range tests {
MoveZeroes(test.input)
ret := test.input
ok := SliceEqual(ret, test.output)
if ok {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", test.output, ret)
}
}
}