qvd
qvd

Reputation: 1027

Remove an element in an array

This is my attempt at this problem, how would I move the 0's to the end of the array? I tried swapping the 0 elements with the end elements and well that wasn't it...

public void removeMiddle()  {
    int pos = values.length/2;
    int n = values.length
    if (n%2 == 0)  {
        int fMid = pos - 1;
        values[pos] = 0;
        values fMid = 0;
    } else  {
        int j = n-1;
        int k = j/2;
        int l = k+1;
        int m = n-l;
        values[m] = 0;
    }
}

Array  =  {5, 2, 7, 9, 1, 3, 2, 4}
result =  [5, 2, 7, 0, 0, 3, 2, 4]
Expected: [5, 2, 7, 3, 2, 4, 0, 0]

Array  =  {5, 2, 7, 9, 1, 3, 2}
result =  [5, 2, 7, 0, 1, 3, 2]
Expected: [5, 2, 7, 1, 3, 2, 0]

Upvotes: 0

Views: 102

Answers (5)

MaVRoSCy
MaVRoSCy

Reputation: 17839

maybe you can use the LinkedList structure and add all non 0 elements of your array at the start of it and all 0's at the end.

    //initial array
    Integer[] array ={1,2,5,8,0,9,10};

    //converted array to List
    ArrayList<Integer> inputList= new ArrayList<Integer>(Arrays.asList(array));

    //secondary list 
    LinkedList<Integer> outputList = new <Integer>LinkedList();


    for(Integer x:inputList){
        int val= Integer.parseInt(x.toString());
        if(val !=0){
            //add non 0 values at the start
            outputList.addFirst(x);
        }else{
            //add 0's at the end
            outputList.addLast(x);
        }
    }

    //convert back to array
    Integer[] outputArray = new Integer[outputList.size()];
    outputArray = outputList.toArray(outputArray);

Upvotes: 0

Achintya Jha
Achintya Jha

Reputation: 12843

Try this: I think its easy to understand and implement.

public static void main(String[] args) {
    int[] arr = { 5, 0, 7, 9, 1, 3, 0 };
    int index = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != 0) {
            arr[index++] = arr[i];
        }

    }

    Arrays.fill(arr, index, arr.length, 0);
    System.out.println(Arrays.toString(arr));
}

Input:

{ 5, 0, 7, 9, 1, 3, 0 }

Output:

[5, 7, 9, 1, 3, 0, 0]

Upvotes: 0

Pratik Singal
Pratik Singal

Reputation: 40

As said by someone earlier you can Convert array to List, remove zeroes, add them back, and convert list back to array or if you want it from scratch and you know the length of the array then just make one array (say array1) and scan the original array (say array) till the end of the array. If the array contains non-zero number just insert it in the array(array1). Once you are done with scanning just add zeros to the remaining array index.

Hope this might help you.

Upvotes: 0

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Convert array to List, remove zeroes, add them back, and convert list back to array.

Upvotes: 1

NPE
NPE

Reputation: 500257

Hint: use System.arraycopy() followed by setting the last element to zero.

Alternatively, use a loop.

Upvotes: 1

Related Questions