Move Zeroes
LeetCode 283 · View on LeetCode
Same-direction two pointers. The slow pointer tracks where the next non-zero value should go. Swap to keep non-zero order intact and push zeroes to the end.
package main
import "fmt"
func moveZeroes(nums []int) {
slow := 0
for fast := 0; fast < len(nums); fast++ {
if nums[fast] != 0 {
nums[slow], nums[fast] = nums[fast], nums[slow]
slow++
}
}
}
func main() {
a := []int{0, 1, 0, 3, 12}
moveZeroes(a)
fmt.Println(a) // [1 3 12 0 0]
b := []int{0, 0, 1}
moveZeroes(b)
fmt.Println(b) // [1 0 0]
c := []int{4, 0, 5, 0, 0, 6}
moveZeroes(c)
fmt.Println(c) // [4 5 6 0 0 0]
}