【华为OD机试】寻找身高相近的小朋友(排序算法实现Java&Python&C++&JS)
题目描述:
给定一个学生信息列表,每个学生信息由姓名和身高组成。要找到身高最接近的小友。如果有多对小友身高相同,则输出字典序最小的一对。
输入描述:
学生信息列表,每个学生信息由姓名和身高组成,姓名和身高由空格分隔,学生信息由换行分隔。
输出描述:
找到身高最接近的小友的信息,姓名和身高之间用空格分隔。
示例输入:
Bob 120
Alice 130
Jane 110
示例输出:
Jane 110 Bob 120
解决方案:
Java 代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] info = scanner.nextLine().split(" ");
students.add(new Student(info[0], Integer.parseInt(info[1])));
}
Student[] closestFriends = findClosestFriends(students);
System.out.println(closestFriends[0].name + " " + closestFriends[0].height + " " + closestFriends[1].name + " " + closestFriends[1].height);
}
private static Student[] findClosestFriends(List<Student> students) {
students.sort(Comparator.comparingInt(s -> s.height));
int minDiff = Integer.MAX_VALUE;
Student[] closest = new Student[2];
for (int i = 1; i < students.size(); i++) {
int diff = Math.abs(students.get(i).height - students.get(i - 1).height);
if (diff < minDiff) {
minDiff = diff;
closest[0] = students.get(i - 1);
closest[1] = students.get(i);
}
}
return closest;
}
static class Student {
String name;
int height;
public Student(String name, int height) {
this.name = name;
this.height = height;
}
}
}
Python 代码实现:
import sys
def find_closest_friends(students):
students.sort(key=lambda s: s.height)
min_diff = sys.maxsize
closest = [None, None]
for i in range(1, len(students)):
diff = abs(students[i].height - students[i - 1].height)
if diff < min_diff:
min_diff = diff
closest[0] = students[i - 1]
closest[1] = students[i]
return closest
class Student:
def __init__(self, name, height):
self.name = name
self.height = height
if __name__ == "__main__":
students = []
for line in sys.stdin:
name, height = line.split()
students.append(Student(name, int(height)))
closest_friends = find_closest_friends(students)
print(f"{closest_friends[0].name} {
评论已关闭