在 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
}
}
最佳答案
这很简单,并且不重复任何元组:
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)
}
https://stackoverflow.com/questions/28532186/