某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉。
输入格式
输入在第一行给出正整数 N,取值在 (0,105];随后 N 行,每行给出 1 个人的姓名(由不超过 5 个英文字母组成的字符串)、以及按 yyyy/mm/dd
(即年/月/日)格式给出的生日。题目保证最年长和最年轻的人没有并列。
输出格式
在一行中顺序输出有效生日的个数、最年长人和最年轻人的姓名,其间以空格分隔。
输入样例
5
John 2001/05/12
Tom 1814/09/06
Ann 2121/01/30
James 1814/09/05
Steve 1967/11/20
输出样例
3 Tom John
Java 代码
1.(4 分,部分正确:测试点 0,答案错误)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[][] peoples = new String[n][2];
int maxIndex, minIndex, cnt;
maxIndex = minIndex = cnt = 0;
for (int i = 0; i < n; i++) {
peoples[i][0] = in.next();
peoples[i][1] = in.next();
if (peoples[i][1].compareTo("1814/09/06") >= 0
&& peoples[i][1].compareTo("2014/09/06") <= 0) {
cnt ++;
if (peoples[maxIndex][1].compareTo(peoples[i][1]) > 0) {
maxIndex = i;
} else if (peoples[minIndex][1].compareTo(peoples[i][1]) < 0) {
minIndex = i;
}
}
}
System.out.print(cnt);
if (cnt != 0) {
System.out.print(" " + peoples[maxIndex][0]+ " " + peoples[minIndex][0]);
}
}
}
Bug 1
对于查找过程中最大最小值的初始值问题,本代码中,maxIndex 和 minIndex 都赋初值为 0,但在索引位置为 0 的数据可能为不合理(非法)数据,将不合理数据与合理的数据进行取极值,有可能取到的是 索引位置为 0 的非法数据!
Bug 2
可能有一条数据集市最大值也是最小值,但用 if - else if “非此即彼”的话会将这种可能排除在外!
2.(16 分,部分正确,测试点 4,运行超时)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] oldPeople = new String[] {"","2014/09/06"};
String[] youngPeople = new String[] {"", "1814/09/06"};
int cnt = 0;
while (n-- != 0) {
String name = in.next();
String birthday = in.next();
if (birthday.compareTo("1814/09/06") >= 0 && birthday.compareTo("2014/09/06") <= 0) {
cnt ++;
if (oldPeople[1].compareTo(birthday) >= 0) {
oldPeople[0] = name;
oldPeople[1] = birthday;
}
if (youngPeople[1].compareTo(birthday) <= 0) {
youngPeople[0] = name;
youngPeople[1] = birthday;
}
}
}
System.out.print(cnt);
if (cnt != 0) {
System.out.print(" " + oldPeople[0]+ " " + youngPeople[0]);
}
}
}
C/C++ 代码
#include <iostream>
using namespace std;
int main() {
int n;int cnt = 0;
cin >> n;
string oldPeople[2] = {"", "2014/09/06"};
string youngPeople[2] = {"", "1814/09/06"};
while (n--) {
string name, birthday;
cin >> name >> birthday;
if (birthday >= "1814/09/06" && birthday <= "2014/09/06") {
cnt ++;
if (oldPeople[1] >= birthday) {
oldPeople[0] = name;
oldPeople[1] = birthday;
}
if (youngPeople[1] <= birthday) {
youngPeople[0] = name;
youngPeople[1] = birthday;
}
}
}
cout << cnt;
if (cnt != 0) {
cout << " " << oldPeople[0] << " " << youngPeople[0];
}
return 0;
}