【发布时间】:2018-11-16 17:36:47
【问题描述】:
我正在使用 Scala 中的应用程序 Data Structures 进行练习,我在数组上编写了第二个问题,如下所示:
/**
* Given n non-negative integers a1, a2, ..., an, where each represents a
* point at coordinate (i, ai), n vertical lines are drawn such that
* the two endpoints of line i is at (i, ai) and (i, 0).
*
* Find two lines, which together with x-axis forms a container such
* that the container contains the most water.
*
* Efficiency: O(n)
*
* @param a Array of line heights
* @return Maximum area
*/
def maxArea(a: Array[Int]): Int = {
@tailrec
def go(l: Int, r: Int)(max: Int): Int = {
if (l >= r) max
else {
val currArea = math.min(a(l), a(r)) * (r - l)
val area = math.max(max, currArea)
log debug s"Current area for $l and $r is $currArea"
log debug s"Max area till now is $area"
if (a(l) < a(r)) go(l + 1, r)(area)
else go(l, r - 1)(area)
}
}
go(0, a.size - 1)(0)
}
我想知道是否有更好的替代方法来编写递归函数作为遍历数组的一种方式,因为someone once told me将递归称为函数式编程的 GOTO。
您可以在GitHub查看完整的源代码
提前谢谢你。
【问题讨论】:
-
重新递归/goto,有兴趣的可以the related paper
-
@eukaryota 已删除
标签: arrays scala performance data-structures