题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
package main
import (
"fmt"
"sort"
)
type Student struct {
Name string
Score int
}
func sortStudentByScore(students []Student, orderType int) []Student {
if orderType == 1 {
sort.SliceStable(students, func(i, j int) bool {
return students[i].Score < students[j].Score
})
}
if orderType == 0 {
sort.SliceStable(students, func(i, j int) bool {
return students[i].Score > students[j].Score
})
}
return students
}
func main() {
var n int
var orderType int
fmt.Scan(&n, &orderType)
var students []Student
for i:=0; i<n; i++ {
var name string
var score int
fmt.Scan(&name, &score)
students = append(students, Student{Name: name, Score: score})
}
sortedStudents := sortStudentByScore(students, orderType)
for _, student := range sortedStudents {
fmt.Printf("%s %d\n", student.Name, student.Score)
}
}
// 本题输入为每行一个字符串和整数,所以采用:fmt.Scan(&name, &score)
