Me
- 遍历所有数组,统计0的个数
- 倒着把零写入数组末尾
func moveZeroes(nums []int) {var count, j intfor _, key := range nums {if key == 0 {count++} else{nums[j] = keyj++}}for i:=len(nums) - count; i < len(nums); i++ {nums[i] = 0}
}
最优解(快慢指针)
减少了数组赋值次数
func moveZeroes3(nums []int) {j := 0for i := 0; i < len(nums); i++ {if nums[i] == 0 {continue}nums[j] = nums[i]if i != j {nums[i] = 0}j++}
}