题解 | 成绩排序

成绩排序

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

package main

import (
	"errors"
	"fmt"
)

/**

这道题题目本身描述就有问题,
有问题的第一点就是
除此之外,保证输入数据中不存在重复的学生姓名。
既然保证输入数据中不存在重复的学生姓名,为什么还有一个用例输入了两个b 一个分数是10分,另一个是44分,这个保证是题目给我们保证还是我们需要自己编码保证,这里就没说清楚
第二点描述问题:题目只要求按照成绩进行排序,但是没说明成绩相同时,应该怎么进行排序,由于是笔试,也无法与出题方进行交流,但实际上题目是要求按照输入顺序对成绩相同的数据进行二次排序的,这一点应该在题目中明示。
*/

type Comparable interface {
	Compare(other Comparable) int
	GetInputSort() int
}

type NameAndScore struct {
	Name  string
	Score int
	InputSort int
}

func (ns *NameAndScore) Compare(other Comparable) int {
	otherNs, ok := other.(*NameAndScore)
	if !ok {
		panic(errors.New("cannot compare two class objects"))
	}
	if ns == otherNs {
		return 0
	}
	if ns.Score > otherNs.Score {
		return 1
	}
	if ns.Score < otherNs.Score {
		return -1
	}
	return 0
}

func (ns *NameAndScore) GetInputSort() int {
	return ns.InputSort
}


func ComparableSort[T Comparable](list []T, isAsc bool) {
	l := len(list)
	for i := 0; i < l; i++ {
		for j := i + 1; j < l; j++ {
			o1, o2 := list[i], list[j]
			cmpRes := o1.Compare(o2)
			if !isAsc {
				cmpRes = -cmpRes
			}
			if cmpRes == 0 && o1.GetInputSort()>o2.GetInputSort() {
				cmpRes = 1
			}
			if cmpRes > 0 {
				list[i], list[j] = o2, o1
			}
		}
	}
}

func GetScoresFromCmd(num int) []*NameAndScore {
	nameScores := make([]*NameAndScore, 0)
	for i := 0; i < num; i++ {
		name, score := "", 0
		_, _ = fmt.Scan(&name, &score)
		nameScores = append(nameScores, &NameAndScore{
			Name:  name,
			Score: score,
			InputSort: i,
		})
	}
	return nameScores
}

func main() {
	num, sortStyle := 0, 0
	_, _ = fmt.Scan(&num, &sortStyle)
	nss := GetScoresFromCmd(num)
	ComparableSort(nss, sortStyle == 1)
    for _,ns := range nss {
        fmt.Println(ns.Name,ns.Score)
    }
}

全部评论

相关推荐

04-15 13:42
四川大学 Java
蹲蹲offerrr:快投吧,有点晚现在
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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