本文主要是介绍Scala实现移除数组中第一个负数之后的所有负数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com1import scala.collection.mutable.ArrayBuffer/*** @author yangxin_ryan* Scala实现移除数组中第一个负数之后的所有负数* 版本一*/
object Test51 {def main(args: Array[String]): Unit = {val arrBuffer = ArrayBuffer[Int]()arrBuffer += (1, 2, 3, 4, 5, -1, -3, -5, -7)var foundFirstNegative = falsevar arrLength = arrBuffer.lengthvar index = 0while(index < arrLength) {if (arrBuffer(index) >= 0) {index += 1} else {if (!foundFirstNegative) {foundFirstNegative = trueindex += 1} else {arrBuffer.remove(index)arrLength -= 1}}}println(arrBuffer)}}
package com1import scala.collection.mutable.ArrayBuffer/*** @author yangxin_ryan* Scala实现移除数组中第一个负数之后的所有负数* 版本二* 基于版本一优化*/
object Test52 {def main(args: Array[String]): Unit = {val arrBuffer = ArrayBuffer[Int]()arrBuffer += (1, 2, 3, 4, 5, -1, -3, -5, -7)var foundFirstNegative = falseval keepIndexes = for (i <- arrBuffer.indices if !foundFirstNegative || arrBuffer(i) >= 0) yield {print(arrBuffer(i))if (arrBuffer(i) < 0) foundFirstNegative = truei}println(keepIndexes)for (i <- keepIndexes.indices) {arrBuffer(i) = arrBuffer(keepIndexes(i))}arrBuffer.trimEnd(arrBuffer.length - keepIndexes.length)println(arrBuffer)}
}
这篇关于Scala实现移除数组中第一个负数之后的所有负数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!