题目
题目链接 PTA | 程序设计类实验辅助教学平台
AC答案1
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
String startId = "";
String endId = "";
int startHourAnswer = 24;
int startMinuteAnswer = 24;
int startSecondAnswer = 24;
int endHourAnswer = 0;
int endMinuteAnswer = 0;
int endSecondAnswer = 0;
while (N-- > 0) {
String[] s = scanner.nextLine().split(" ");
String id = s[0];
String[] start = s[1].split(":");
int startHour = Integer.parseInt(start[0]);
int startMinute = Integer.parseInt(start[1]);
int startSecond = Integer.parseInt(start[2]);
if (startHour < startHourAnswer) {
startId = id;
startHourAnswer=startHour;
startMinuteAnswer=startMinute;
startSecondAnswer=startSecond;
} else if (startHour == startHourAnswer && startMinute < startMinuteAnswer) {
startId = id;
startHourAnswer=startHour;
startMinuteAnswer=startMinute;
startSecondAnswer=startSecond;
} else if (startHour == startHourAnswer && startMinute == startMinuteAnswer && startSecond < startSecondAnswer) {
startId = id;
startHourAnswer=startHour;
startMinuteAnswer=startMinute;
startSecondAnswer=startSecond;
}
String[] end = s[2].split(":");
int endHour = Integer.parseInt(end[0]);
int endMinute = Integer.parseInt(end[1]);
int endSecond = Integer.parseInt(end[2]);
if (endHour > endHourAnswer) {
endId = id;
endHourAnswer=endHour;
endMinuteAnswer=endMinute;
endSecondAnswer=endSecond;
} else if (endHour == endHourAnswer && endMinute > endMinuteAnswer) {
endId = id;
endHourAnswer=endHour;
endMinuteAnswer=endMinute;
endSecondAnswer=endSecond;
} else if (endHour == endHourAnswer && endMinute == endMinuteAnswer && endSecond > endSecondAnswer) {
endId = id;
endHourAnswer=endHour;
endMinuteAnswer=endMinute;
endSecondAnswer=endSecond;
}
}
System.out.println(startId + " " + endId);
}
}
AC答案2
参考了柳神的思路,给时、分、秒各个不同的权重加起来,避免了上面解答中逐个判断时、分、秒的尴尬
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
String startId = "";
String endId = "";
int startAnswer = 100000000;
int endAnswer = 0;
while (N-- > 0) {
String[] s = scanner.nextLine().split(" ");
String id = s[0];
String[] start = s[1].split(":");
int startHour = Integer.parseInt(start[0]);
int startMinute = Integer.parseInt(start[1]);
int startSecond = Integer.parseInt(start[2]);
int tempStart = startHour * 3600 + startMinute * 60 + startSecond;
if (tempStart < startAnswer) {
startId = id;
startAnswer = tempStart;
}
String[] end = s[2].split(":");
int endHour = Integer.parseInt(end[0]);
int endMinute = Integer.parseInt(end[1]);
int endSecond = Integer.parseInt(end[2]);
int tempEnd = endHour * 3600 + endMinute * 60 + endSecond;
if (tempEnd > endAnswer) {
endId = id;
endAnswer = tempEnd;
}
}
System.out.println(startId + " " + endId);
}
}