LeetCode Intersection Of Two Arrays(Runtime: 2 ms, faster than 95.28% of Java online . Memory Usage: 39.3 MB, less than 32.15% of Java online submissions .)
class Solution {
public int[] intersection(int[] arr1, int[] arr2) {
int n1=arr1.length;
int n2=arr2.length;
HashSet<Integer> set=new HashSet<Integer>();
for(int i=0;i<n1;i++){
set.add(arr1[i]);
}
//System.out.println("Set 1 elements are: ");
//set.forEach(System.out::println);
HashSet<Integer> set2=new HashSet<Integer>();
HashSet<Integer> set3=new HashSet<Integer>();
for(int i=0;i<n2;i++){
set2.add(arr2[i]);
}
//System.out.println("Set 2 elements are: ");
//set2.forEach(System.out::println);
int inter=0;
int index=0;
for(int x : set2){
if(set.contains(x)){
inter++;
set3.add(x);
}
}
int aa[]=new int[set3.size()];
//System.out.print("Intersection elements are: ");
//System.out.println(inter);
for(int x:set3){
aa[index++]=x;
}
//for(int i=0;i<aa.length;i++){
//System.out.print(aa[i]+" ");
//}
return aa;
}
}
Comments
Post a Comment