
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.
1using System;
2using System.Collections.Generic;
3
4class Intersection {
5 public static int[] IntersectionOfArrays(int[] nums1, int[] nums2) {
6 HashSet<int> set1 = new HashSet<int>(nums1);
7 HashSet<int> resultSet = new HashSet<int>();
8
9 foreach (int num in nums2) {
10 if (set1.Contains(num)) {
11 resultSet.Add(num);
12 }
13 }
14
15 int[] result = new int[resultSet.Count];
16 resultSet.CopyTo(result);
17 return result;
18 }
19
20 static void Main() {
21 int[] nums1 = {4, 9, 5};
22 int[] nums2 = {9, 4, 9, 8, 4};
23 int[] result = IntersectionOfArrays(nums1, nums2);
24 Console.WriteLine(string.Join(" ", result));
25 }
26}This C# solution uses the HashSet collection. It first builds set1 from nums1 and then iterates over nums2, checking for elements in set1 and adding any matches to resultSet. The result set is then copied to an array and returned.
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.