The
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> :p aste// entering paste mode (ctrl-d tofinish ) var foundFirstNegative = falseval keepIndexes = for (i <- 0 untila.length if !foundfirstnegative | | a (i) > 0) # Description 1yield {if (A (i) < 0) foundfirstnegative =true; i # Description 2}for (i <- 0 until Keepindexes.length) A (i) = a (keepindexes (i)) # description 3a.trimend (a.length - Keepindexes.length) # Description 4 // exiting paste mode, now interpreting. Foundfirstnegative: boolean = truekeepindexes:scala.collection.immutable.indexedseQ[int] = vector (0, 1, 2, 3, 4,5) Scala> ares4: Scala.collection.mutable.arraybuffer[int] = arraybuffer (1,&NBSP;2,&NBSP;3,&NBSP;5,&NBSP;-1,&NBSP;2)
Algorithm Description: Avoid the traditional multiple moving array, remove multiple times , the above code design advantage is to find the element that does not meet the criteria index, and then uniformly delete these elements.
illustration 1: The first negative number and all positive numbers will pass through the if guard;
illustration 2: The first negative number passes the If Guard, enters the description 2 code, the foundfirstnegative is set to true, Subsequent negative numbers pass through the If Guard section, and I and if are independent and do not surround the block with blocks;
illustration 3: Set the first KEEPINDEXES.LENGTH element in a to the corresponding integer and the first negative number;
Description 4 : Delete a in keepindexes.length–1 The element that follows the position, and the remainder is the element that is being asked.
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1965431
Remove all negative numbers after the first negative number in an array