|
| 1 | +package me.ramswaroop.arrays; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by IntelliJ IDEA. |
| 7 | + * |
| 8 | + * @author: ramswaroop |
| 9 | + * @date: 10/20/15 |
| 10 | + * @time: 11:34 PM |
| 11 | + */ |
| 12 | +public class SymmetricDifference { |
| 13 | + |
| 14 | + /** |
| 15 | + * Returns the symmetric difference between array {@param a1} |
| 16 | + * and array {@param a2}. |
| 17 | + * <p/> |
| 18 | + * SYMMETRIC DIFFERENCE refers to the numbers which are present in |
| 19 | + * only one of the arrays and not both. |
| 20 | + * |
| 21 | + * @param a1 |
| 22 | + * @param a2 |
| 23 | + * @return |
| 24 | + */ |
| 25 | + public static int[] getSymmetricDifference(int[] a1, int[] a2) { |
| 26 | + int index = 0; |
| 27 | + int[] res = new int[a1.length + a2.length]; |
| 28 | + |
| 29 | + Arrays.sort(a1); |
| 30 | + Arrays.sort(a2); |
| 31 | + |
| 32 | + for (int i = 0, j = 0; i < a1.length || j < a2.length; ) { |
| 33 | + if (j >= a2.length) { |
| 34 | + res[index++] = a1[i]; |
| 35 | + i++; |
| 36 | + } else if (i >= a1.length) { |
| 37 | + res[index++] = a2[j]; |
| 38 | + j++; |
| 39 | + } else if (a1[i] < a2[j]) { |
| 40 | + res[index++] = a1[i]; |
| 41 | + i++; |
| 42 | + } else if (a2[j] < a1[i]) { |
| 43 | + res[index++] = a2[j]; |
| 44 | + j++; |
| 45 | + } else { |
| 46 | + i++; |
| 47 | + j++; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return Arrays.copyOf(res, index); |
| 52 | + } |
| 53 | + |
| 54 | + public static void main(String a[]) { |
| 55 | + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{2, 4, 5}))); |
| 56 | + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{5, 6, 7}))); |
| 57 | + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{5, 6, 7, 8}))); |
| 58 | + System.out.println(Arrays.toString(getSymmetricDifference(new int[]{1, 2, 3, 4}, new int[]{1, 2, 3, 4}))); |
| 59 | + } |
| 60 | +} |
0 commit comments