class Solution:
def intersection(self, nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
return list(set1 & set2)
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set1(nums1.begin(), nums1.end());
unordered_set<int> result;
for (int num : nums2) {
if (set1.count(num)) {
result.insert(num);
}
}
return vector<int>(result.begin(), result.end());
}
};
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) set1.add(num);
Set<Integer> result = new HashSet<>();
for (int num : nums2) {
if (set1.contains(num)) result.add(num);
}
int[] resArr = new int[result.size()];
int i = 0;
for (int num : result) resArr[i++] = num;
return resArr;
}
}
var intersection = function(nums1, nums2) {
const set1 = new Set(nums1);
const result = new Set();
for (let num of nums2) {
if (set1.has(num)) {
result.add(num);
}
}
return Array.from(result);
};
You are given two arrays of integers, nums1
and nums2
. The task is to return an array containing the unique elements that appear in both nums1
and nums2
.
Each element in the result must be unique, and the result can be returned in any order.
Key constraints:
nums1 = [1,2,2,1]
and nums2 = [2,2]
, then the intersection is [2]
.
At first glance, you might think to compare every element in nums1
with every element in nums2
to find matches. This brute-force approach works but is inefficient for large arrays.
To optimize, we realize that we only care about unique values and whether they exist in both arrays. Sets are perfect for this because they automatically handle uniqueness and provide fast lookup.
The idea is: if we can quickly check if a value from one array exists in the other, we can efficiently build the intersection. This leads us to consider using hash sets (or similar structures) to store the elements and perform quick membership checks.
We'll use sets to solve this problem efficiently. Here are the steps:
We use sets because:
Let's use the example nums1 = [4,9,5]
, nums2 = [9,4,9,8,4]
.
set1 = {4, 9, 5}
set2 = {4, 8, 9}
set1
and set2
? 4
and 9
.[9, 4]
or [4, 9]
(order does not matter).Step-by-step, we see that converting to sets filters out duplicates and allows us to efficiently find which elements are shared.
Brute-force approach:
nums1
with each element of nums2
.The optimized approach is much faster, especially for large arrays, because set operations are highly efficient.
The key insight for this problem is to use sets to handle uniqueness and enable fast lookups. By converting both arrays to sets and finding their intersection, we solve the problem efficiently and elegantly. This approach avoids unnecessary comparisons and leverages data structures designed for exactly this kind of task.
In summary: use sets for uniqueness and speed, and simply return their intersection as the result.