In: Computer Science
Java Program
Sequential Search
You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Do not use any import sort packages.
Input: In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.
Output: Print C in a line.
Constraints
Sample Input 1
5 1 2 3 4 5 3 3 4 1
Sample Output 1
3
Sample Input 2
3 3 1 2 1 5
Sample Output 2
0
Sample Input 3
5 1 1 2 2 3 2 1 2
Sample Output 3
2
PROGRAM with comments :
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;
public class Solution{
public static void main(String args[]){
Scanner sc = new
Scanner(System.in);
int n =
Integer.parseInt(sc.nextLine()); //Taking input n
String[] s = sc.nextLine().split("
"); //Taking 2nd line input as
string
int q =
Integer.parseInt(sc.nextLine()); //Taking input q
String[] t = sc.nextLine().split("
"); //Taking 4th line input as
string
int S[] = new int[n];
//Declaring S array of intgers to store S
int T[] = new int[q];
//Declaring T array of intgers to store T
int i=0;
for(String ele : s){
//Loop to populate S array
S[i++] =
Integer.parseInt(ele); //Converting
string to integer and storing it to S array
}
int j=0;
for(String ele : t){
//Loop to populate S array
T[j++] =
Integer.parseInt(ele); //Converting
string to integer and storing it to T array
}
Set<Integer> set = new
HashSet<Integer>(); //Set to store result
set
for(int sec: T){
//Outer loop to iterate through T
for(int first:
S){ //Inner loop to iterate through S
if(sec == first) //checking if
current element of T is equal to the element of S
set.add(sec);
//if equal, adding it to the set
}
}
System.out.println(set.size());
//printing out the number of elements in the set (the result)
}
}
SCREENSHOT :