
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
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.