IntersectionOfTwoArrays.java
· 1.0 KiB · Java
Исходник
import java.util.*;
public class IntersectionOfTwoArrays {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
HashSet<Integer>s=new HashSet<Integer>();
System.out.println("Enter the no. of elements in array a");
int n1=sc.nextInt();
System.out.println("Enter the no. of elements in array b");
int n2=sc.nextInt();
int a[]=new int[n1];
int b[]=new int[n2];
System.out.println("Enter the elements of array a : ");
for(int i=0; i<n1; i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the elements of array b : ");
for(int i=0; i<n2; i++)
{
b[i]=sc.nextInt();
}
for(int i=0; i<n1; i++)
s.add(a[i]);
int result=0;
for(int j=0; j<n2; j++)
{
if(s.contains(b[j])) {
result++;
s.remove(b[j]);
}
}
System.out.println("Required no. of common elements are : "+result);
}
}
1 | import java.util.*; |
2 | |
3 | public class IntersectionOfTwoArrays { |
4 | public static void main(String args[]) |
5 | { |
6 | Scanner sc=new Scanner(System.in); |
7 | HashSet<Integer>s=new HashSet<Integer>(); |
8 | System.out.println("Enter the no. of elements in array a"); |
9 | int n1=sc.nextInt(); |
10 | System.out.println("Enter the no. of elements in array b"); |
11 | int n2=sc.nextInt(); |
12 | int a[]=new int[n1]; |
13 | int b[]=new int[n2]; |
14 | System.out.println("Enter the elements of array a : "); |
15 | for(int i=0; i<n1; i++) |
16 | { |
17 | a[i]=sc.nextInt(); |
18 | } |
19 | System.out.println("Enter the elements of array b : "); |
20 | for(int i=0; i<n2; i++) |
21 | { |
22 | b[i]=sc.nextInt(); |
23 | } |
24 | for(int i=0; i<n1; i++) |
25 | s.add(a[i]); |
26 | int result=0; |
27 | for(int j=0; j<n2; j++) |
28 | { |
29 | if(s.contains(b[j])) { |
30 | result++; |
31 | s.remove(b[j]); |
32 | } |
33 | } |
34 | System.out.println("Required no. of common elements are : "+result); |
35 | } |
36 | } |
37 |