Given two arrays, write a function to compute their intersection.
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1==null || nums2==null){
return null;
}
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums1.length;i++){
if(!map.containsKey(nums1[i])){
map.put(nums1[i], 1);
}else{
map.put(nums1[i],map.get(nums1[i])+1);
}
}
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<nums2.length;i++){
if(map.containsKey(nums2[i]) && map.get(nums2[i])>0){
list.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i])-1);
}
}
int[] result=new int[list.size()];
for(int i=0;i<list.size();i++){
result[i]=list.get(i);
}
return result;
}
public int[] intersection2(int[] nums1, int[] nums2){
if(nums1==null || nums2==null){
return null;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int index1=0;
int index2=0;
ArrayList<Integer> list=new ArrayList<Integer>();
while(index1<nums1.length && index2<nums2.length){
if(nums1[index1]>nums2[index2]){
index2++;
}else if(nums1[index1]<nums2[index2]){
index1++;
}else{
list.add(nums1[index1]);
index1++;
index2++;
}
}
int[] result=new int[list.size()];
for(int i=0;i<list.size();i++){
result[i]=list.get(i);
}
return result;
}