
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.
1function intersection(nums1, nums2) {
2 let set1 = new Set(nums1);
3 let resultSet = new Set();
4
5 for (let num of nums2) {
6 if (set1.has(num)) {
7 resultSet.add(num);
8 }
9 }
10 return Array.from(resultSet);
11}
12
13let nums1 = [4, 9, 5];
14let nums2 = [9, 4, 9, 8, 4];
15let result = intersection(nums1, nums2);
16console.log(result);This JavaScript solution uses the ES6 Set object to store nums1 elements and determine the intersection by iterating over nums2. Matches are added to resultSet, which is then converted to an array for the final result.
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
class Intersection {
public static int[] IntersectionOfArrays(int[] nums1, int[] nums2) {
Array.Sort(nums1);
Array.Sort(nums2);
int i = 0, j = 0;
int[] tempResult = new int[nums1.Length + nums2.Length];
int index = 0;
while (i < nums1.Length && j < nums2.Length) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
if (index == 0 || tempResult[index - 1] != nums1[i]) {
tempResult[index++] = nums1[i];
}
i++;
j++;
}
}
int[] result = new int[index];
Array.Copy(tempResult, 0, result, 0, index);
return result;
}
static void Main() {
int[] nums1 = {4, 9, 5};
int[] nums2 = {9, 4, 9, 8, 4};
int[] result = IntersectionOfArrays(nums1, nums2);
Console.WriteLine(string.Join(" ", result));
}
}This C# approach sorts the input arrays and uses two pointers to find intersections, ensuring uniqueness by checking the latest added value. The result is copied from a temporary array to the correct size.