移除數組中第一個負數後的全部負數

scala> val a = ArrayBuffer[Int](1, 2,3, 5, -1, 2, -3, -5)
a: scala.collection.mutable.ArrayBuffer[Int]= ArrayBuffer(1, 2, 3, 5, -1, 2, -3
, -5)
 
scala> :paste
// Entering paste mode (ctrl-D tofinish)
 
var foundFirstNegative = false
val keepIndexes = for (i <- 0 untila.length if !foundFirstNegative || a(i) > 0) # 說明1
yield {
if (a(i) < 0) foundFirstNegative =true; i # 說明2
}
for (i <- 0 until keepIndexes.length)a(i) = a(keepIndexes(i)) # 說明3
a.trimEnd(a.length - keepIndexes.length)# 說明4
 
// Exiting paste mode, now interpreting.
 
foundFirstNegative: Boolean = true
keepIndexes:scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4,
5)
scala> a
res4:scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 5, -1, 2)

算法說明:避免傳統屢次移動數組,屢次remove,上述代碼設計優勢在於統一找出不知足條件的元素index,而後統一刪除這些元素。java

說明1:第一個負數和全部正數都會經過if守衛;算法

說明2:第一個負數經過if守衛,進入說明2代碼,將foundFirstNegative置爲true,後續的負數則通不過if守衛部分,且iif是獨立的,並未使用塊包圍;數組

說明3:將a中前keepIndexes.length個元素置爲對應的整數和第一個負數;ide

說明4:刪掉akeepIndexes.length – 1位置後面的元素,剩下的即爲所求元素。spa

相關文章
相關標籤/搜索