349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
//TODO: you don't really need the set after sort arrays.
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int i=0, j=0;
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
while( i < nums1.length && j < nums2.length){
if(nums1[i] > nums2[j]){
j++;
}else if(nums1[i] < nums2[j]){
i++;
}else{
set.add(nums1[i]);
i++;j++;
}
}
int[] res = new int[set.size()];
int k =0;
for(Integer v : set){
res[k++] = v;
}
return res;
}
}
You can also use set
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> res = new HashSet<>();
for(int v : nums1){
set.add(v);
}
for(int v : nums2){
if(set.contains(v)) res.add(v);
}
int[] r = new int[res.size()];
int k = 0;
for(int i : res){
r[k++] = i;
}
return r;
}
}