Home > database >  Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting them to right -
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting them to right -

Time:11-11

condition is 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 void duplicateZeros(int[] arr) {
        int length = arr.length;
        for(int i=0;i<length;i  ){
            if(arr[i]==0){
              arr[i 1]=arr[i];

            }
        }
        
        
    }
}

error is

java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
  at line 6, Solution.duplicateZeros
  at line 54, __DriverSolution__.__helper__
  at line 84, __Driver__.main

why i am getting this error?

CodePudding user response:

Try this.

public static void duplicateZeros(int[] arr) {
    int length = arr.length;
    for (int i = 0; i < length; i  ) {
        if (arr[i] == 0) {
            System.arraycopy(arr, i, arr, i   1, length - i - 1);
              i;
        }
    }
}

public static void main(String[] args) {
    int[] a = { 1, 0, 2, 3, 0, 4, 5, 0 };
    duplicateZeros(a);
    System.out.println(Arrays.toString(a));
}

output:

[1, 0, 0, 2, 3, 0, 0, 4]

CodePudding user response:

Your solution is wrong, and i 1 will cause an index out of bounds on the last i.

You want some result index, named j here:

     [1,0,2,3,0,4,5,0] 
  i   0 1 2 3 4 5 6 7   ---> for i
  j?  0   1 2   3 4    5 6 7
     [1,  2,3,  4,5,   0,0,0] 
  • Related