2016-02-12 58 views
-4

我想要寫功能版本用於求出一對具有給定sum.the元素是命令性代碼:功能碼到低於一個必須在階

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

研究的Standard Library

def findPairs(arr:Array[Int],sum:Int): List[Array[Int]] = 
    arr.combinations(2).filter(_.sum == sum).toList 
相關問題