题目描述
小明今年升学到小学一年级,来到新班级后发现其他小朋友们身高参差不齐,然后就想基于各小朋友和自己的身高差对他们进行排序,请帮他实现排序。
输入描述:
第一行为正整数 h和n,0<h<200 为小明的身高,0<n<50 为新班级其他小朋友个数。
第二行为n个正整数,h1 ~ hn分别是其他小朋友的身高,取值范围0<hi<200,且n个正整数各不相同。
输出描述:
输出排序结果,各正整数以空格分割,
和小明身高差绝对值最小的小朋友排在前面,
和小明身高差绝对值最大的小朋友排在后面,
如果两个小朋友和小明身高差一样,则个子较小的小朋友排在前面。
示例 :
输入:
100 10 95 96 97 98 99 101 102 103 104 105
输出:
99 101 98 102 97 103 96 104 95 105
说明:
小明身高100,班级学生10个,身高分别为95 96 97 98 99 101 102 103 104 105,按身高差排序后结果为:99 101 98 102 97 103 96 104 95 105。
解题思路:
思路一:
新建一个List集合,来保存输入的身高,使用list集合的.sort()方法对list集合进行遍历排序,如果身高差相同,取更小的身高放在前面,如果身高差不同,则取更小的身高差放在前面.
思路二:
通过双重for循环遍历集合,计算两个元素之间的身高差,如果身高差相同,则把更小的身高放在前面,如果身高差不同,则取更小的身高差放在前面.
题解:
题解一:
public class Test {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int mingHeight=scanner.nextInt();
int numFriends=scanner.nextInt();
List<Integer> friendHeights=new ArrayList<>();
for (int i = 0; i < numFriends; i++)
{
int friendHeight = scanner.nextInt();
friendHeights.add(friendHeight);
}
friendHeights.sort((h1, h2) -> {
int difference = Math.abs(h1 - mingHeight);
int difference2 = Math.abs(h2 - mingHeight);
//如果身高差相同
if (difference==difference2)
{
//负数 h1更小 h1在前
//0 两数相同 位置不变
//正数 h1更大 h1在后
return h1-h2;
}
//如果身高差不同,比较身高差
//负数,h1更小,h1在前
//正数 h1更大, h1在后
return difference-difference2;
});
for (Integer friendHeight : friendHeights)
{
System.out.print(friendHeight+ " ");
}
}
}
题解二:
public class Dec13 {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int mingHeight=scanner.nextInt();
int numFriends=scanner.nextInt();
List<Integer> friendHeights=new ArrayList<>();
for (int i = 0; i < numFriends; i++)
{
int friendHeight = scanner.nextInt();
friendHeights.add(friendHeight);
}
for (int i = 0; i <friendHeights.size(); i++)
{
for (int j = i+1; j < friendHeights.size(); j++)
{
Integer h1 = friendHeights.get(i);
Integer h2 = friendHeights.get(j);
Integer diff1 = Math.abs(h1-mingHeight);
Integer diff2 = Math.abs(h2-mingHeight);
int temp;
if ((diff1==diff2&&h2<h1)||diff1>diff2)
{
temp=h1;
friendHeights.set(i,h2);
friendHeights.set(j,temp);
}
}
}
for (Integer friendHeight : friendHeights)
{
System.out.print(friendHeight+ " ");
}
}
}