-4

我想编写功能版本来查找具有给定总和的元素对。下面是命令式代码:

object ArrayUtil{

  def findPairs(arr:Array[Int],sum:Int) ={
    val MAX = 50
    val binmap:Array[Boolean] = new Array[Boolean](MAX)

    for(i <- 0 until arr.length){

      val temp:Int = sum-arr(i);
         if (temp>=0 && binmap(temp))
           {
            println("Pair with given sum " + sum + " is (" + arr(i) +", "+temp+")");
           }
      binmap(arr(i)) = true;
       }
    }
}
4

1 回答 1

4

研究标准库

def findPairs(arr:Array[Int],sum:Int): List[Array[Int]] =
  arr.combinations(2).filter(_.sum == sum).toList
于 2016-02-12T07:54:27.300 回答