给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
注意:请不要在超过该数组长度的位置写入元素。
要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。
示例 1:
输入:[1,0,2,3,0,4,5,0]
输出:null
解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]
var duplicateZeros = function(arr) {
const n = arr.length
let i = j = 0
while (i < n && j < n) {
if (arr[i] === 0) {
j += 2
} else {
j++
}
i++
}
i--
j--
if (j === n) {
arr[j - 1] = 0
j -= 2
i--
}
while (j >= 0) {
arr[j] = arr[i]
if (arr[i] === 0) {
arr[j - 1] = 0
j -= 2
} else {
j--
}
i--
}
};
function duplicateZeros(arr: number[]): void {
const n = arr.length
let i = 0, j = 0
while (i < n && j < n) {
if (arr[i] === 0) j += 2
else j++
i++
}
i--
if (j === n + 1) {
arr[j - 2] = 0
j -= 2
i--
}
while (j--) {
arr[j] = arr[i]
if (arr[i--] === 0) {
arr[j - 1] = 0
j--
}
}
};
func duplicateZeros(arr []int) {
n, i, j := len(arr), 0, 0
for i < n && j < n {
if arr[i] == 0 {
j += 2
} else {
j++
}
i++
}
i--
j--
if j == n {
arr[j - 1] = 0
j -= 2
i--
}
for j > 0 {
arr[j] = arr[i]
if arr[i] == 0 {
arr[j - 1] = 0
j -= 2
} else {
j--
}
i--
}
}
class Solution {
function duplicateZeros(&$arr) {
$n = count($arr);
$i = $j = 0;
while ($i < $n && $j < $n) {
if ($arr[$i] === 0) $j += 2;
else $j++;
$i++;
}
$i--;
$j--;
if ($j === $n) {
$arr[$j - 1] = 0;
$j -= 2;
$i--;
}
while ($j > 0) {
$arr[$j] = $arr[$i];
if ($arr[$i] === 0) {
$arr[$j - 1] = 0;
$j -= 2;
} else {
$j--;
}
$i--;
}
}
}
class Solution {
public void duplicateZeros(int[] arr) {
int n = arr.length;
int i = 0, j = 0;
while (i < n && j < n) {
if (arr[i] == 0) j += 2;
else j++;
i++;
}
i--;
j--;
if (j == n) {
arr[j - 1] = 0;
j -= 2;
i--;
}
while (j > 0) {
arr[j] = arr[i];
if (arr[i] == 0) {
arr[j - 1] = 0;
j-=2;
} else {
j--;
}
i--;
}
}
}
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
n, i, j = len(arr), 0, 0
while i < n and j < n:
if arr[i] == 0: j += 2
else: j += 1
i += 1
i -= 1
j -= 1
if j == n:
arr[j - 1] = 0
j -= 2
i -= 1
while j > 0:
arr[j] = arr[i]
if arr[i] == 0:
arr[j - 1] = 0
j -= 2
else: j -= 1
i -= 1
void duplicateZeros(int* arr, int arrSize){
int i = 0, j = 0;
while (i < arrSize && j < arrSize) {
if (arr[i] == 0) j += 2;
else j++;
i++;
}
i--;
j--;
if (j == arrSize) {
arr[j - 1] = 0;
j -= 2;
i--;
}
while (j > 0) {
arr[j] = arr[i];
if (arr[i] == 0) {
arr[j - 1] = 0;
j -= 2;
} else {
j--;
}
i--;
}
}
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int n = arr.size(), i = 0, j = 0;
while (i < n && j < n) {
if (arr[i] == 0) j += 2;
else j++;
i++;
}
i--;
j--;
if (j == n) {
arr[j - 1] = 0;
j -= 2;
i--;
}
while (j > 0) {
arr[j] = arr[i];
if (arr[i] == 0) {
arr[j - 1] = 0;
j -= 2;
} else {
j--;
}
i--;
}
}
};
public class Solution {
public void DuplicateZeros(int[] arr) {
int i = 0, j = 0, n = arr.Length;
while (i < n && j < n) {
if (arr[i] == 0) j += 2;
else j++;
i++;
}
i--;
j--;
if (j == n) {
arr[j - 1] = 0;
j -= 2;
i--;
}
while (j > 0) {
arr[j] = arr[i];
if (arr[i] == 0) {
arr[j - 1] = 0;
j -= 2;
} else {
j--;
}
i--;
}
}
}