题解 | 成绩排序
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
// 0 降序 1 升序
int op = in.nextInt();
// 输入的数据,用什么存储呢?二维数组?map? 先二微数组吧,然后自定义排序器?
String[][] arr = new String[n][2];
// 接受输入的数据
for(int i =0;i <n;i++)
{
arr[i][0] = in.next();
arr[i][1] = in.next();
}
// 自定义排序器
Arrays.sort(arr,(a,b)->{
int sa = Integer.parseInt(a[1]);
int sb = Integer.parseInt(b[1]);
return op == 0 ? sb -sa:sa-sb;
});
// 遍历
for(String[] s : arr)
{
System.out.println(s[0]+" "+s[1]);
}
}
}
关键就是 自定义排序器。根据 op 去判断是否逆序输出。
