import java.util.Arrays;
/**
* Created by Roman on 8/27/14.
*/
public class Main {
public static void main(String[] args) {
int[] x = {1, 4};
int[] y = {1, 2};
int[] results = getUnion(x, y);
System.out.println(Arrays.toString(results));
}
private static int[] getIntersection(int[] x, int[] y) {
int xL = x.length;
int yL = y.length;
int[] results = new int[Math.min(xL, yL)];
int count = 0;
int i = 0;
int j = 0;
while (i < xL && j < yL) {
if (x[i] != y[j]) {
if (x[i] <= y[j]) {
i++;
} else {
j++;
}
} else {
results[count++] = x[i];
i++;
j++;
}
}
int[] intersection = new int[count];
System.arraycopy(results, 0, intersection, 0, count);
return intersection;
}
private static int[] getUnion(int[] x, int[] y) {
int xL = x.length;
int yL = y.length;
int[] results = new int[xL + yL];
int count = 0;
int i = 0, j = 0;
int lastValue;
if (xL > 0 && yL > 0) {
if (x[0] <= y[0]) {
lastValue = results[count++] = x[i++];
} else {
lastValue = results[count++] = y[j++];
}
while (i < xL && j < yL) {
if (x[i] != y[j]) {
if (x[i] <= y[j]) {
if (x[i] != lastValue) {
lastValue = results[count++] = x[i++];
} else {
i++;
}
} else {
if (y[j] != lastValue) {
lastValue = results[count++] = y[j++];
} else {
j++;
}
}
} else {
if (x[i] != lastValue) {
lastValue = results[count++] = x[i];
i++;
j++;
}
}
}
if (i > j) {
for (int index = j; index < yL; index++) {
if (y[index] != lastValue) {
lastValue = results[count++] = y[index];
}
}
} else {
for (int index = i; index < xL; index++) {
if (x[index] != lastValue) {
lastValue = results[count++] = x[index];
}
}
}
} else {
return new int[]{};
}
int[] union = new int[count];
System.arraycopy(results, 0, union, 0, count);
return union;
}
}