A_K_A
A_K_A

Reputation: 1

How to make a void method that will remove and replace duplicates from integer array in java

I'm trying to remove duplicates from an int array in Java. This method is void and should only alter the array I'm given. I'm also supposed to replace each duplicate with 0.

//array's duplicates are replaced with zero
//array is returned
public static void removeDuplicates(int[] array) {
    //create a temp variable to compare all other other int values in result array
    int temp;
    //double for loop iterates through array and compares each value to temp.
    for(int i = 0; i < array.length; i++) {
        temp = array[i];
        for(int j = 0; j < array.length; j++) {
            if ((array[j] == temp) && (j+1 < array.length)) {
                array[j] = 0;
            }
        }
    }
}

This is what I've tried so far. It runs, however, I'm not able to replace all of my duplicates with zero. For example, if I have an array {2,2}, then I'll get an array {0,2} which is not what I want. Rather, I should be getting {0,0}. I've tried drawing this out and still can't find the problem.

Upvotes: 0

Views: 89

Answers (1)

WJS
WJS

Reputation: 40044

Temp holds the value(s) to be deleted but only if it is a duplicate. The inner loop must go from i+1 to the end to see if other values of temp exist. If so, zero them out. But since the first one is also equal to temp it must be deleted too if it was a duplicate.

Change your loops to the following:

for(int i = 0; i < array.length-1; i++) {
     temp = array[i];
     for(int j = i+1; j < array.length; j++) {
         if (array[j] == temp) {
             array[j] = 0;
             array[i] = 0; // remove the first one too
         }
     }
 }

Upvotes: 1

Related Questions