March 12, 2024

Java Problem Solution: Find the Intersection of two Arrays in Java


import java.util.Arrays;
public class ArrayIntersection {
    public static void main(String[] args) {
        int[] arr1 = {1, 8, 3, 4, 5};
        int[] arr2 = {4, 5, 6, 7, 8, 5, 1};
        int[] intersection = findIntersection(arr1, arr2);
        System.out.print("Intersection of arrays: ");
        for (int num : intersection) {
            System.out.print(num + " ");
        }
    }
    public static int[] findIntersection(int[] arr1, int[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        int minLength = Math.min(len1, len2);
        int maxLength = Math.max(len1, len2);
        int[] result = new int[minLength];
        int index = 0;
        // Determine the smaller and larger arrays
        int[] smallerArray = (len1 <= len2) ? arr1 : arr2;
        int[] largerArray = (len1 > len2) ? arr1 : arr2;
        for (int num : smallerArray) {
            if (contains(num, largerArray)) {
                result[index++] = num;
            }
        }
        return Arrays.copyOf(result, index);
    }
    public static boolean contains(int value, int[] arr) {
        for (int num : arr) {
            if (num == value) {
                return true;
            }
        }
        return false;
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.