【问题标题】:Sort a list given a list of indices给定索引列表对列表进行排序
【发布时间】:2015-07-25 10:59:30
【问题描述】:

假设我有一个无序列表

val unsorted = List("third", "second", "fourth", "first")

我还有另一个列表,上面列表的索引以正确的顺序排列

val ids = List(3, 1, 0, 2)

如何使用这些索引对unsorted 进行排序以获得此结果

List("first", "second", "third", "fourth")

【问题讨论】:

    标签: list scala sorting


    【解决方案1】:

    只需将 id 映射到未排序列表本身。

    scala> val sorted = ids map unsorted.toIndexedSeq
    sorted: List[String] = List(first, second, third, fourth)
    

    unsorted 转换为IndexedSeq 不是必需的,但正如@gzm0 在下面指出的那样,它可以防止此操作成为O(n^2)

    【讨论】:

    • 考虑先在unsorted上调用toIndexedSeq,否则这将是O(n^2)
    猜你喜欢
    • 2011-03-16
    • 2016-09-10
    • 2012-09-07
    • 2022-01-08
    • 2011-05-09
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多