題目

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

題目大意

給你一個長度固定的整數數組 arr,請你將該數組中出現的每個零都複寫一遍,並將其餘的元素向右平移。注意:請不要在超過該數組長度的位置寫入元素。要求:請對輸入的數組 就地 進行上述修改,不要從函數返回任何東西。

解題思路

  • 給一個固定長度的數組,把數組元素為 0 的元素都往後複製一遍,後面的元素往後移,超出數組長度的部分刪除。
  • 簡單題,按照題意,用 append 和 slice 操作即可。

參考代碼

func duplicateZeros(arr []int) {
	for i := 0; i < len(arr); i++ {
		if arr[i] == 0 && i+1 < len(arr) {
			arr = append(arr[:i+1], arr[i:len(arr)-1]...)
			i++
		}
	}
}