
Sponsored
Sponsored
This approach utilizes hash sets to efficiently track and identify unique intersections between the two arrays. By converting one of the arrays into a set, we can check for existence of elements in constant time, and we store intersections in another set to ensure uniqueness.
Time complexity is O(n + m) for inserting and checking elements, with n and m being the sizes of nums1 and nums2 respectively. Space complexity is O(n + m) for the two sets used.
1import java.util.HashSet;
2import java.util.Set;
3
4public class Intersection {
5 public static int[] intersection(int[] nums1, int[] nums2) {
6 Set<Integer> set1 = new HashSet<>();
7 Set<Integer> resultSet = new HashSet<>();
8
9 for (int num : nums1) {
10 set1.add(num);
11 }
12
13 for (int num : nums2) {
14 if (set1.contains(num)) {
15 resultSet.add(num);
16 }
17 }
18
19 int[] result = new int[resultSet.size()];
20 int i = 0;
21 for (int num : resultSet) {
22 result[i++] = num;
23 }
24 return result;
25 }
26
27 public static void main(String[] args) {
28 int[] nums1 = {4, 9, 5};
29 int[] nums2 = {9, 4, 9, 8, 4};
30 int[] result = intersection(nums1, nums2);
31 for (int num : result) {
32 System.out.print(num + " ");
33 }
34 }
35}This Java solution uses two HashSet objects to find unique intersections: one for the elements of nums1 and another to store the intersection results. Elements of nums2 are checked against set1 for inclusion and added to resultSet if present.
This approach sorts both arrays and uses two pointers to identify the intersection. The sorted order ensures that we can efficiently find common elements in a single pass through both arrays.
Time complexity is O(n log n + m log m) due to sorting, where n and m are the sizes of nums1 and nums2. Space complexity is O(n + m) for storing the sorted arrays.
1
This C solution sorts both arrays and uses two pointers to traverse them. The pointers move forward when differences are found, and add elements to the result only if they are equal and haven't been added before, ensuring uniqueness.