题解 | 成绩排序

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        HashMap<Integer, String> map = new HashMap<>();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int size = Integer.parseInt(in.nextLine());
            int flag = Integer.parseInt(in.nextLine());
            int[][] score = new int[size][2];//姓名编号,成绩
            for (int i = 0; i < size; i++) {
                String[] nameAndScore = in.nextLine().split("\\s+");
                score[i][0] = i;
                score[i][1] = Integer.parseInt(nameAndScore[1]);
                map.put(i, nameAndScore[0]);
            }
            Arrays.sort(score, (o1, o2) -> {
                if (flag == 0) {
                    return o2[1] -
                    o1[1];//按第二列降序排列,如果相等的话,返回0,顺序不变
                } else {
                    return o1[1] - o2[1];//按第二列升序
                }
            });
            for (int i = 0; i < size; i++) {
                System.out.println(map.get(score[i][0]) + " " + score[i][1]);
            }
        }
    }
}

全部评论

相关推荐

03-12 12:33
嘉应学院 Python
堆肥大王:认可你的做法,但无产阶级的兄弟们也希望你能过的更好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务