I must be confused somewhere. I change the arr variable given by LeetCode to the desired array, but my output still states the original input.
Here's the input:
[1,0,2,3,0,4,5,0]
Here's the output:
[1,0,2,3,0,4,5,0]
Here's my expected output:
[1,0,0,2,3,0,0,4]
Here's my actual stdout:
newArr variable: 1, 0, 0, 2, 3, 0, 0, 4,
arr variable: 1, 0, 0, 2, 3, 0, 0, 4,
I think my issue is me not changing the value of arr out side of the scope. Maybe? I'm unsure of what my issue is.
class Solution {
public void duplicateZeros(int[] arr) {
int[] newArr = new int[arr.length];
int length = 0;
for (int x = 0 ; x < arr.length ; x++) {
if (length == arr.length) {
break;
}
else if (arr[x] != 0) {
newArr[length] = arr[x];
}
else if (arr[x] == 0) {
newArr[length] = arr[x];
if (length + 1 < arr.length) {
newArr[length + 1] = arr[x];
length++;
}
}
length++;
}
System.out.print("newArr variable: ");
for (int num : newArr) {
System.out.print(num + ", ");
}
arr = null;
arr = newArr;
System.out.print("\narr variable: ");
for (int num : arr) {
System.out.print(num + ", ");
}
}
}