Remove all negative numbers after the first negative number in an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.