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;
}