(UVA) CD - Solution 2
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2949
If you want to see another solution for this problem, click here.
The difference between the first solution and this one is that here instead of using a Binary Search, it is being used a HashSet to check the common CDs that Jack and Jill have.
import java.io.*;
import java.util.*;
class Main {
public static void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCDsJack = sc.nextInt();
int numCDsJill = sc.nextInt();
while (numCDsJack != 0 || numCDsJill != 0) {
int[] cdsJack = new int[numCDsJack];
for (int i = 0; i < numCDsJack; i++) {
cdsJack[i] = sc.nextInt();
}
HashSet<Integer> cdsJill = new HashSet<>();
for (int i = 0; i < numCDsJill; i++) {
cdsJill.add(sc.nextInt());
}
int countCommon = 0;
for (int i = 0; i < numCDsJack; i++) {
if (cdsJill.contains(cdsJack[i])) {
countCommon++;
}
}
System.out.println(countCommon);
numCDsJack = sc.nextInt();
numCDsJill = sc.nextInt();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
If you want to see another solution for this problem, click here.
The difference between the first solution and this one is that here instead of using a Binary Search, it is being used a HashSet to check the common CDs that Jack and Jill have.
import java.io.*;
import java.util.*;
class Main {
public static void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCDsJack = sc.nextInt();
int numCDsJill = sc.nextInt();
while (numCDsJack != 0 || numCDsJill != 0) {
int[] cdsJack = new int[numCDsJack];
for (int i = 0; i < numCDsJack; i++) {
cdsJack[i] = sc.nextInt();
}
HashSet<Integer> cdsJill = new HashSet<>();
for (int i = 0; i < numCDsJill; i++) {
cdsJill.add(sc.nextInt());
}
int countCommon = 0;
for (int i = 0; i < numCDsJack; i++) {
if (cdsJill.contains(cdsJack[i])) {
countCommon++;
}
}
System.out.println(countCommon);
numCDsJack = sc.nextInt();
numCDsJill = sc.nextInt();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment