Finding the intersection of two arrays.
Here’s a Java program that finds the intersection of two arrays:
import java.util.*; public class ArrayIntersection { public static void main(String[] args) { int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = {4, 5, 6, 7, 8}; int[] intersection = findIntersection(arr1, arr2); System.out.print("Intersection: "); for (int num : intersection) { System.out.print(num + " "); } } public static int[] findIntersection(int[] arr1, int[] arr2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int num : arr1) { set1.add(num); } for (int num : arr2) { if (set1.contains(num)) { set2.add(num); } } int[] intersection = new int[set2.size()]; int index = 0; for (int num : set2) { intersection[index++] = num; } return intersection; } }
This program defines a method called `findIntersection()` that takes two integer arrays as input and returns the intersection of the arrays as another integer array. It uses sets to efficiently find the common elements between the two arrays. The `main()` method demonstrates how to use the `findIntersection()` method and prints the intersection to the console.
In the given example, the output will be:
Intersection: 4 5
Here, the intersection of arrays `arr1` and `arr2` is `{4, 5}`.
No comments yet! You be the first to comment.