如何在列表中找到成绩最好的学生? [英] How to find students with the best grades in a list?
问题描述
假设,我有一个Students
列表. Students
具有诸如name
,birth date
,grade
等的字段.如何在Scala中找到具有最佳grade
的Students
?
Suppose, I have a list of Students
. Students
have fields like name
, birth date
, grade
, etc. How would you find Students
with the best grade
in Scala?
例如:
List(Student("Mike", "A"), Student("Pete", "B"), Student("Paul", A))"
我想得到
List(Student("Mike", "A"), Student("Paul", A))
很明显,我可以找到max grade
(在上面的列表中为"A"),然后找到filter
列表
Obviously, I can find the max grade
("A" in the list above) and then filter
the list
students.filter(_.grade == max_grade)
此解决方案是O(N)
,但在列表上运行了两次.您能提出更好的解决方案吗?
This solution is O(N)
but runs over the list twice. Can you suggest a better solution?
推荐答案
在列表上运行两次可能是最好的方法,但是如果您 insist 只能运行一次以上的解决方案,您可以使用折叠(此处适用于空列表):
Running over the list twice is probably the best way to do it, but if you insist on a solution that only runs over once, you can use a fold (here works on empty lists):
(List[Student]() /: list){ (best,next) => best match {
case Nil => next :: Nil
case x :: rest =>
if (betterGrade(x,next)) best
else if (betterGrade(next,x)) next :: Nil
else next :: best
}}
如果您不熟悉褶皱,请在答案的此处中进行描述.当您通过集合(例如列表)时,它们是积累某些东西的一般方法.如果您不熟悉匹配,则可以使用isEmpty
和head
做同样的事情.如果希望学生按照与原始列表中出现的顺序相同的顺序,请在最后运行.reverse
.
If you are unfamiliar with folds, they are described in an answer here. They're a general way of accumulating something as you pass over a collection (e.g. list). If you're unfamiliar with matching, you can do the same thing with isEmpty
and head
. If you want the students in the same order as they appeared in the original list, run .reverse
at the end.
这篇关于如何在列表中找到成绩最好的学生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!