[scala]删除immutable.List 中的 第一次出现的最小值:

scala  删除remove immutable List 中的 从左边 第一个  first  最小值 min:

这样:



val x = List(2, 1, 4, 1, 3)
x diff List(x.min)


x: List[Int] = List(2, 1, 4, 1, 3)
res7: List[Int] = List(2, 4, 1, 3)


还有这样子


scala> x
res15: List[Int] = List(2, 1, 4, 1, 3)


scala>
val (l, _ :: tail) = x span {x.min != _}
l: List[Int] = List(2)
tail: List[Int] = List(4, 1, 3)


scala> l ::: tail
res16: List[Int] = List(2, 4, 1, 3)


scala>



  嗯,是这样子
scala> x
res15: List[Int] = List(2, 1, 4, 1, 3)


scala> val (l, _ :: tail) = x span {x.min !=}
l: List[Int] = List(2)
tail: List[Int] = List(4, 1, 3)


scala> l ::: tail
res16: List[Int] = List(2, 4, 1, 3)


scala>



其他:

----------

scala> val a = List (3,2,2,3,5)
a: List[Int] = List(3, 2, 2, 3, 5)
scala> a.lastIndexOf(a.min)
res16: Int = 2


scala> a.
splitAt ( a. lastIndexOf (a.min))
res17: (List[Int], List[Int]) = (List(3, 2),List(2, 3, 5))


scala> res17
res19: (List[Int], List[Int]) = (List(3, 2),List(2, 3, 5)).
scala> res17._1
++ res17._2.tail
res20: List[Int] = List(3, 2, 3, 5)



----------
scala> val l = List(7,9,3,4,2,6,2,7)
l: List[Int] = List(7, 9, 3, 4, 2, 6, 2, 7)


scala> val min = l.min
min: Int = 2


scala> l.
takeWhile (_ != min) ++ l. dropWhile (_ != min).tail
res5: List[Int] = List(7, 9, 3, 4, 6, 2, 7)



----------





----------
scala> var alreadyFiltered = false
alreadyFiltered: Boolean = false


scala> l.filter(x => if(alreadyFiltered) true else if(x == min) {alreadyFiltered = true; false} else true )
res10: List[Int] = List(7, 9, 3, 4, 6, 2, 7)


用个变量帮忙,可以写成filter

----------

教主提供:


真正的库代码写法

 O(n)
跟List长度成正比 

 def dropMin(list: List[Int]): List[Int] = {
    if (list.isEmpty) return Nil


    val b = new ListBuffer[Int]
    var min = list.head
    var these = list.tail


    while (!these.isEmpty) {
      if (these.head < min) {
        b += min
        min = these.head
      } else {
        b += these.head
      }
      these = these.tail
    }
    b.toList
  }
  dropMin(List(3, 4, 2, 5, 2, 8))





















你可能感兴趣的:(scala)