Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
My Solution
We first add all elements of num1 to a HashSet to get all unique values. We then check if the elements of num2 are in num1 and if they are we add them to another HashSet. Finally we create our output array and add all the values of our intersection HashSet to the array.
Time complexity is O(m+n), where m is the length of nums1 and n is the length of nums2 because we iterate through both arrays. Space complexity is also O(m+n) because of the space required for both HashSets.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> unique = new HashSet<>();
Set<Integer> inter = new HashSet<>();
for (int num : nums1) {
unique.add(num);
}
for (int num : nums2) {
if (unique.contains(num)) {
inter.add(num);
}
}
int[] out = new int[inter.size()];
int i = 0;
for (int val : inter) {
out[i] = val;
i++;
}
return out;
}
}