349 . Intersection of Two Arrays
Easy
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.
7ms:
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> s1 = new HashSet<Integer>();
HashSet<Integer> s2 = new HashSet<Integer>();
List<Integer> re = new ArrayList<Integer>();
for(int x:nums1){
s1.add(x);
}
for(int y:nums2){
s2.add(y);
}
for(int z:s1){
if(s2.contains(z))
re.add(z);
}
Object[] res = re.toArray();
int[] fir = new int[res.length];
for(int i=0;i<res.length;i++){
fir[i] = (int) res[i];
}
return fir;
}
6ms:
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer,Integer> m1 = new HashMap<Integer,Integer>();
for(int x:nums1){
m1.put(x, 1);
}
List<Integer> res = new ArrayList<Integer>();
for(int y:nums2){
Integer sa = m1.get(y);
if(sa!=null&&sa!=0){
res.add(y);
m1.put(y, 0);
}
}
int[] ress = new int[res.size()];
for(int i=0;i<res.size();i++){
ress[i] = res.get(i);
}
return ress;
}
350 . Intersection of Two Arrays II
Easy
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?