zoukankan      html  css  js  c++  java
  • 考研机试 9.成绩排序

    时间:2021/02/24 

    一.题目描述

    用一维数组存储学号和成绩,然后,按成绩排序输出。

    输入描述

    输入第一行包括一个整数N(1<=N<=100),代表学生的个数。
    接下来的N行每行包括两个整数p和q,分别代表每个学生的学号和成绩。

     输出描述

    按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。
    如果学生的成绩相同,则按照学号的大小进行从小到大排序。

    题目链接

    https://www.nowcoder.com/practice/3f27a0a5a59643a8abf0140b9a8cf1f7?

    tpId=40&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey 

    二.算法

    题解

    由于对于每一个学生来说有两个属性,分别是学号和成绩,所以有两种解题的思路。第一种是用两个数组分别存放学号和成绩,首先用冒泡排序对成绩数组按从小到大的顺序进行排序,这里要注意,由于学号和成绩是一一对应的关系,所以对成绩数组进行交换的同时也要对学号数组进行交换。之后再对成绩数组进行遍历,找到成绩相同的区间,在这个区间中按学号从小到大进行排序,最后输出。可以通过Arrays类的静态方法sort对数组进行排序。对第二种解题思路是下面的代码,用一个静态内部类Student来存放学号和成绩,通过继承Comparable类并重写compareTo方法来定义比较规则,这里要注意,不能使用int数据类型,只能使用Integer数据类型(因为它重写了compareTo方法),还要重写toString方法来方便输出结果。代码中可能存在异常,但并不影响运行。

    代码

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Scanner;
     
    public class Main {
        public static void main(String[] args) {
            
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            ArrayList<Student> list = new ArrayList<>();
            
            for (int i = 0; i < n; i++){
                list.add(new Student(scanner.nextInt(),scanner.nextInt()));
            } 
            Collections.sort(list);
            for (Student student : list){
                System.out.println(student);
            } 
        }
         
        public static class Student implements Comparable<Student>{
            Integer stuNumber;
            Integer score;
     
            public Student(Integer stuNumber,Integer score){
                this.stuNumber = stuNumber;
                this.score = score;
            }
    
            public int compareTo(Student o) {
               return this.score.equals(o.score) ? stuNumber.compareTo(o.stuNumber) : score.compareTo(o.score);
            }
    
            public String toString() {
                return stuNumber + " " + score;
            }
        }
    }
  • 相关阅读:
    php程序员面试经验
    模板引擎(smarty)知识点总结五
    模板引擎(smarty)知识点总结三
    js计算字数
    phpexcel导出成绩表
    phpexcel用法(转)
    模板引擎(smarty)知识点总结
    apache泛域名解析
    对象的解构赋值
    解构赋值
  • 原文地址:https://www.cnblogs.com/machi12/p/14443048.html
Copyright © 2011-2022 走看看