scala - Scala 中 N 的三和

在 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/

相关文章:

oracle - 增加 SQL Developer 导出中的行数

python-2.7 - 如何使用python检查机器人框架中的字典是否为空

angularjs - 使用angularjs突出显示表格行

r - R中的嵌套foreach循环,其中内部循环返回一个矩阵

angularjs - 作为指令的表行在 angularjs 中显示在表上下文之外

php - Twig Loader 命名空间

assembly - 汇编语言中的 or 和 ori 有什么区别?

java - try-with-resource资源创建的执行顺序

c# - 生成员工卡

java - 正则表达式用引号替换字符串