Move Zeroes To The Back In Place
Compact non-zero values to the front with two indexes that swap in place, pushing every zero to the back while preserving the relative order of values.
Code
package main
import "fmt"
// move zeroes to the back in place: slow pins the next non-zero slot
func moveZeroes(nums []int) []int {
slow := 0
for fast, v := range nums {
if v != 0 {
nums[slow], nums[fast] = nums[fast], nums[slow]
slow++
}
}
return nums
}
func main() {
values := []int{0, 1, 0, 3, 12}
moveZeroes(values)
fmt.Println(values)
// 没有零值时交换退化为自交换,原顺序保持不变
all := []int{5, 6, 7}
moveZeroes(all)
fmt.Println(all)
}Move Zeroes To The Back In Place: reading the source
Everything you would edit lives in moveZeroes and main; the rest is wiring.
The file repeats itself only inside for fast, v := range nums.
Watch out for
- Imports go no further than the standard library’s fmt — no third-party dependency list to manage.
Applying it
The callable surface: func moveZeroes(nums []int) []int
The entry point wires moveZeroes together — run it once and the whole demo flows.
Statements that matter
func moveZeroes(nums []int) []int {
slow := 0
for fast, v := range nums {
if v != 0 {
nums[slow], nums[fast] = nums[fast], nums[slow]
slow++
}
}
return nums
}
func main() {
values := []int{0, 1, 0, 3, 12}
moveZeroes(values)
fmt.Println(values)
// 没有零值时交换退化为自交换,原顺序保持不变
all := []int{5, 6, 7}
moveZeroes(all)
fmt.Println(all)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Move Zeroes To The Back In Place?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.