import java util Arrays Created by Roman on 27 14 public class Main pu

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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;
}
}