Topic:
Given an array, the "0" is filtered out and placed at the end, leaving the remaining elements in the original order.
Requirements:
1, cannot produce an array copy
2. Move array elements as little as possible
Package Mainimport "FMT" Func Main () {slice: = []int{0,1,0,3,12,0,0,1,2,3,0,0,1,0,1,0,8,9,0,0,0}fmt. Println ("Final array:", move (slice))}func move (a []int) []int{var l int = len (a) temp: = 0 Count: = 0for i:= 0;i < L;i ++{if A[i] = = 0{fmt. PRINTLN ("Array before swapping position:", a) Count++temp = a[i]for J: = i; j < (L-1); J++{a[j] = A[j + 1]}a[l-1] = tempfmt. Println ("The array after the position is changed:", a) fmt. Println ("----------------")}if count + i < L {if a[i] = = 0 { i-- }}else {return a}} return a}
Output Result:
Array before swapping position: [0 1 0 3 12 0 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0]
Array after position change: [1 0 3 12 0 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0]
----------------
Array before swapping position: [1 0 3 12 0 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0]
Array after position change: [1 3 12 0 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 0 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0]
Array after position change: [1 3 12 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 0 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 0 0 1 0 1 0 8 9 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 0 1 0 1 0 8 9 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 0 1 0 1 0 8 9 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 0 1 0 8 9 0 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 1 0 1 0 8 9 0 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 1 0 8 9 0 0 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 1 1 0 8 9 0 0 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
----------------
Array before swapping position: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
Array after position change: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
----------------
Final array: [1 3 12 1 2 3 1 1 8 9 0 0 0 0 0 0 0 0 0 0 0]
Array-specific element filtering