【牛客刷题】HJ68 成绩排序

题目链接

这题本身就是一个排序题,按照学生成绩排序,成绩一样的按照输入的前后顺序排。

如果用Java,那么利用ArrayList能很轻松的完成:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int b = in.nextInt(); // 0 or 1
            List<Student> list = new ArrayList<>();
            for (int i = 0; i < a; i++) {
                Student student = new Student(in.next(), in.nextInt());
                list.add(student);
            }

            if (b == 1) {
                list.sort(Comparator.comparingInt(Student::getGrade));
            }
            if (b == 0) {
                list.sort((o1, o2) -> o2.getGrade() - o1.getGrade());
            }

            list.forEach(System.out::println);
        }
    }
}

class Student {
    private String name;

    private int grade;

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return this.name + " " + this.grade;
    }
}

但是实际执行时间不容乐观,要169ms。换成Go试试看,实际上也是定义一个数据结构,但是这里要注意一点,一定要加上index表示输入顺序,事实上Java帮我们做了好多事情,一旦换了别的语言要首先适应自己的事情自己做:

package main

import (
	"fmt"
	"sort"
)

type Grade struct {
	name  string
	score int
	index int
}

func main() {
	num := 0
	fmt.Scan(&num)

	flag := 0
	fmt.Scan(&flag)

	var grades []*Grade

	for i := 0; i < num; i++ {
		name := ""
		score := 0
		fmt.Scan(&name, &score)
		grades = append(grades, &Grade{name, score, i})
	}

	if flag == 0 {
		sort.Slice(grades, func(i, j int) bool {
			if grades[i].score == grades[j].score {
				return grades[i].index < grades[j].index
			}
			return grades[i].score > grades[j].score
		})
	} else {
		sort.Slice(grades, func(i, j int) bool {
			if grades[i].score == grades[j].score {
				return grades[i].index < grades[j].index
			}
			return grades[i].score < grades[j].score
		})
	}
	for _, v := range grades {
		fmt.Printf("%s %d\n", v.name, v.score)
	}
}

实际执行时间6ms,真棒

posted @ 2023-02-15 23:12  wingsless  阅读(213)  评论(0编辑  收藏  举报