1089. Duplicate Zeros (重複零)

題目

Given a fixed-length integer array arr, 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 and do not return anything.

複製每個出現的零,將剩餘的值向右移動
不能寫入超出原始陣列長度,對原始陣列修改,不返回任何內容。


Example 1

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

Example 2

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

Constraints:

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 9

我的解題

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public void duplicateZeros(int[] arr) {
Queue<Integer> queue = new LinkedList<Integer>();
for(int i=0;i<arr.length;i++){
queue.offer(arr[i]); //隊列新增arr[i]
if(arr[i] == 0){
queue.offer(0); //若arr[i]==0,則對列新增0
}
arr[i] = queue.poll(); //將對列的值放回陣列
}
}
}