Compsciguy Compsciguy - 4 years ago 137
Java Question

Merge two arrays and remove duplicates in Java

I am having trouble removing the duplicates from two arrays that have been merged into one. I have written the following code that merges the arrays, yet I'm not sure how to remove the duplicates from the final array. Assume the arrays are already sorted.

public static int[] merge(int[] list1, int[] list2) {
int[] result = new int[list1.length + list2.length];

int i = 0;
int j = 0;

for (int k = 0; k < (list1.length + list2.length); k++) {
if (i >= list1.length) {
result[k] = list2[j];
j++;
}
else if (j >= list2.length) {
result[k] = list1[i];
i++;
}
else {
if (list1[i] < list2[j]) {
result[k] = list1[i];
i++;
} else {
result[k] = list2[j];
j++;
}
}
}
return result;
}

Answer Source

Ok, someone hated all the answers. Here's another attempt that combines two stackoverflow q's, combining arrays and removing dupes.

This one runs a good deal faster than my earlier attempt on two lists of a million ints.

public int[] mergeArrays2(int[] arr1, int[] arr2){
    int[] merged = new int[arr1.length + arr2.length];
    System.arraycopy(arr1, 0, merged, 0, arr1.length);
    System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);

    Set<Integer> nodupes = new HashSet<Integer>();

    for(int i=0;i<merged.length;i++){
        nodupes.add(merged[i]);
    }

    int[] nodupesarray = new int[nodupes.size()];
    int i = 0;
    Iterator<Integer> it = nodupes.iterator();
    while(it.hasNext()){
        nodupesarray[i] = it.next();
        i++;
    }



    return nodupesarray;
}

console output:

INFO [main] (TestMergeArray.java:40) - creating two lists of a million ints
DEBUG [main] (TestMergeArray.java:41) - list 1 size : 1000000
DEBUG [main] (TestMergeArray.java:42) - list 2 size : 1000000
INFO [main] (TestMergeArray.java:56) - now merging
INFO [main] (TestMergeArray.java:59) - done, final list size is 864975
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download