Search a List
Completed
Read n names and then q queries. For each query print its index in the list (indexOf) or missing.
Input
n, n names, q, q queries.
Output
q lines.
Example
Input
3 ann bob cy 3 bob zed ann
Output
1 missing 0
Editor
Java
Hints
indexOf uses equals() to compare.
Solution explanation
contains and indexOf scan the list, so they get slower as the list grows - a HashSet or HashMap is faster for big lookups.
Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<String> names = new ArrayList<String>();
for (int i = 0; i < n; i++) {
names.add(sc.next());
}
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
int idx = names.indexOf(sc.next());
System.out.println(idx >= 0 ? String.valueOf(idx) : "missing");
}
}
}