小编use*_*040的帖子

在Scala中创建最小堆的最简单,最有效的方法是什么?

val maxHeap = scala.collection.mutable.PriorityQueue[Int] //Gives MaxHeap
Run Code Online (Sandbox Code Playgroud)

使用Ordering将PriorityQueue转换为minHeap最简洁有效的方法是什么?

scala priority-queue min-heap data-structures

8
推荐指数
1
解决办法
5075
查看次数

flatten和flatMap(身份)之间有什么区别吗?

scala> List(List(1), List(2), List(3), List(4))
res18: List[List[Int]] = List(List(1), List(2), List(3), List(4))

scala> res18.flatten
res19: List[Int] = List(1, 2, 3, 4)

scala> res18.flatMap(identity)
res20: List[Int] = List(1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)

这两个功能有什么区别吗?何时使用一个而不是另一个?有任何权衡吗?

functional-programming scala flatmap

7
推荐指数
2
解决办法
5968
查看次数

Scala/Java错误处理NullPointerException

我正在研究一种从双链接双端队列中获取元素的方法.当链表是空的时候,我得到一个nullpointerexception,我试图弄清楚如何处理它.我正在使用以下代码,但它仍然需要我返回A.任何想法我怎么能得到这个编译?

def peekBack():A = {
  try {
    last.data // return if the list is full if not, catch the nullpointerexception
  } catch {
    case ex: NullPointerException => {
      println("There are no elements in this list.")
         //Error is here, it is requiring me to return something!!!
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

java error-handling scala try-catch nullpointerexception

2
推荐指数
1
解决办法
4486
查看次数

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
  }
}
Run Code Online (Sandbox Code Playgroud)

scala

2
推荐指数
1
解决办法
391
查看次数