Scala 中的三和到 N

use*_*040 2 scala

有没有比这个例子更好的方法来从列表中找到三个在scala中总和为零的数字?现在,我觉得我的函数方式可能不是最有效的,它包含重复的元组。在我当前的示例中,摆脱重复元组的最有效方法是什么?

def secondThreeSum(nums:List[Int], n:Int):List[(Int,Int,Int)] = {
  val sums = nums.combinations(2).map(combo => combo(0) + combo(1) -> (combo(0), combo(1))).toList.toMap

  nums.flatMap { num =>
    val tmp = n - num
    if(sums.contains(tmp) && sums(tmp)._1 != num && sums(tmp)._2 != num) Some((num, sums(tmp)._1, sums(tmp)._2)) else None
  }
}
Run Code Online (Sandbox Code Playgroud)

dhg*_*dhg 5

这非常简单,并且不重复任何元组:

def f(nums: List[Int], n: Int): List[(Int, Int, Int)] = {
  for {
    (a, i) <- nums.zipWithIndex;
    (b, j) <- nums.zipWithIndex.drop(i + 1)
    c <- nums.drop(j + 1)
    if n == a + b + c
  } yield (a, b, c)
}
Run Code Online (Sandbox Code Playgroud)