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;
}
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.
console output:
Here's a technique that iterates the arrays just once and does not use a hash to detect duplicates.
Call your merge method and do the followings. I tested it. It works fine.
`
Can you use ArrayLists? ArrayLists would make this very easy to do.
}