
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.
1#include <iostream>
2#include <vector>
3#include <unordered_set>
4using namespace std;
5
6vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
7 unordered_set<int> set1(nums1.begin(), nums1.end());
8 unordered_set<int> resultSet;
9
10 for (int num : nums2) {
11 if (set1.count(num)) {
12 resultSet.insert(num);
13 }
14 }
15 return vector<int>(resultSet.begin(), resultSet.end());
16}
17
18int main() {
19 vector<int> nums1 = {4, 9, 5};
20 vector<int> nums2 = {9, 4, 9, 8, 4};
21 vector<int> result = intersection(nums1, nums2);
22 for (int num : result) {
23 cout << num << " ";
24 }
25 return 0;
26}This C++ solution uses the STL unordered_set to track elements. It initializes the first set with elements of nums1 and then iterates over nums2 to find common elements, storing them in resultSet for uniqueness. The result is converted to a vector for the return.
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 Python solution sorts the arrays and utilizes two indices to traverse them. It collects common elements uniquely by checking the last added element in the result list before appending.