利用HashSet去重,
HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。
set.add();返回值是一个boolear类型,如果元素重复就返回false
样例
import java.util.HashSet;
import java.util.Scanner;
//set.add(candyType[i]);//返回值是一个boolear类型,如果元素重复就返回false
public class Main {
static int ans = 0;
static String sirId = null;//存储来参加宴会的人的最大年纪的身份证号
static String alumnusId = null;//存储参加宴会并且是校友的最大年纪的身份证号
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//1.用哈希表存下所有校友的身份证号码
int N = input.nextInt();
input.nextLine();
HashSet<String> alumnusSet = new HashSet<>();
for (int i = 0; i < N; i++) {
alumnusSet.add(input.nextLine());
}
//2.接收来参加校友会的所有人士的身份证号
int M = input.nextInt();
input.nextLine();
for (int i = 0; i < M; i++) {
String sir = input.nextLine();
//set.add();返回值是一个boolear类型,如果元素重复就返回false
if (alumnusSet.add(sir)){
//添加成功说明该用户不是校友
check(sir,0);
}else {
ans++;
//添加不成功,说明哈希表中该用户已经存在, 该用户是校友
check(sir,1);
}
}
//3.输出结果
System.out.println(ans);
if (ans == 0){
System.out.println(sirId);
}else {
System.out.println(alumnusId);
}
}
/*
* 通过身份证判断谁的年纪最大
* */
static void check(String id,int how){
String copyId;
if (how == 1){
copyId = alumnusId;
if (alumnusId == null){
alumnusId = id;
return;
}
}else {
copyId = sirId;
if (sirId == null){
sirId = id;
return;
}
}
//得到当前最大的日期的身份证号
int number1 = Integer.parseInt(id.substring(6,14));//当前用户的日期
int number2 = Integer.parseInt(copyId.substring(6,14));//当前最大的日期
if (number1 < number2){
copyId = id;
}
//将当前最大的日期的id给对应的人
if (how == 1){
alumnusId = copyId;
}else {
sirId = copyId;
}
}
}