-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathDuplicateZeros.java
51 lines (40 loc) · 1.11 KB
/
DuplicateZeros.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package Arrays;
import java.util.Arrays;
/*
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]
*/
public class DuplicateZeros {
// 1st approach - O(N) time | O(N) Space
public static void duplicateZeros(int[] arr) {
int len = arr.length;
int[] temparr = new int[len];
int idxans = 0; // track temp output array index
int currid = 0; // track position in original array item
for (int i = 0; i < len; i++) {
if (idxans >= len)
break;
if (arr[currid] != 0 && idxans < len) {
temparr[idxans] = arr[currid];
idxans++;
currid++;
} else if (arr[currid] == 0 && (idxans + 1) < len) {
temparr[idxans] = 0;
idxans++;
temparr[idxans] = 0;
idxans++;
currid++;
}
}
for (int i = 0; i < len; i++) {
arr[i] = temparr[i];
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
duplicateZeros(new int[] { 1, 0, 2, 3, 0, 4, 5, 0 });
duplicateZeros(new int[] { 8, 4, 5, 0, 0, 0, 0, 7 });
duplicateZeros(new int[] { 1, 2, 3 });
}
}