小明今年升學到了小學1年紀來到新班級后,發現其他小朋友身高參差不齊
然后就想基於各小朋友和自己的身高差,對他們進行排序,請幫他實現排序
輸入描述
第一行為正整數 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個 身高分別為
查看代碼
import java.util.*;
public class Demo5 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int h = Integer.parseInt(sc.nextLine().split(" ")[0]);
ArrayList<Integer> res = getList(sc.nextLine());
res.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int d1 = o1 - h > 0 ? o1 - h : h - o1;
int d2 = o2 - h > 0 ? o2 - h : h - o2;
if(d1 == d2)
return o1 - o2;
else
return d1 - d2;
}
});
StringBuilder sb = new StringBuilder();
for(int i : res){
sb.append(i).append(" ");
}
String ans = sb.toString().trim();
System.out.println(ans);
}
private static ArrayList<Integer> getList(String s){
String[] split = s.split(" ");
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < split.length; i++){
list.add(Integer.parseInt(split[i]));
}
return list;
}
}
總結:每種類型都有自己的處理特點,自定義排序是常用ArrayList,對輸出格式的處理常用StringBuilder,
思維自然地分段,將某段獨立的功能獨立出去寫成一個輔助函數,增加可讀性。