你能用我的解决方案让我停下来吗。我写了一些方法它得到了一些ArrayInt,并找到了目标和求和
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
def twoSum(nums: Array[Int], target: Int) : Array[Int] = {
val numSorted = nums.sorted
for (i <- 0 until numSorted.length) {
for (j <- i + 1 until numSorted.length) {
val l = numSorted(i) + numSorted(j)
if (l == target) {
Array(nums.indexOf(numSorted(i)), nums.indexOf(numSorted(j)))
}
}
}
}
val nums = Array(2, 7, 11, 15)
val target = 9
twoSum(nums,target)我的代码是在没有方法twoSum的情况下工作的,但是当我将它放入方法中时,就会出现错误。
type mismatch;
found : Unit
required: Array[Int]发布于 2022-02-14 18:48:10
好吧,您的函数没有返回任何内容,正如注释中所解释的那样(但是在scala中使用return被认为是一种糟糕的实践,因此,我建议您不要这样做)。
我还想提到,这不是一个很好的解决方案,因为它是二次型的(当数组很大时,嵌套循环使得它非常慢).而且,我担心它看起来不太像scala代码。
我建议你这样做:
def twoSum(nums: Array[Int], target: Int) = {
val diffs = nums.map(target - _).zipWithIndex.toMap
nums.zipWithIndex.collectFirst {
case (n, i) if (diffs.get(n).nonEmpty) => Array(i, diffs(n))
}.getOrElse(Array.empty)
}首先,这将创建一个哈希映射,将目标元素和数组元素之间的每一个可能的差异映射到该元素的索引中。然后扫描数组,查找映射中出现的第一个数字:如果映射中的键等于当前元素,则该元素和索引处的元素之和(由映射的值指向)等于目标。
我建议您尝试分别运行这些语句ini并查看它们到底做了什么。
发布于 2022-02-14 18:29:26
在Scala中,函数的最后一行是返回的内容。通常,在其他语言中,这是return x,就像在Scala中一样,它可以只是x,而不需要return关键字。
在您的代码片段中,没有返回值,所以Scala推断类型为Unit,这与返回类型Array[Int]不匹配,所以编译器报告的类型不匹配。
下面是您的代码,并在评论中添加了@Luis建议来解决这个问题。
def twoSum(nums: Array[Int], target: Int) : Array[Int] = {
val numSorted = nums.sorted
for (i <- 0 until numSorted.length) {
for (j <- i + 1 until numSorted.length) {
val l = numSorted(i) + numSorted(j)
if (l == target) {
return Array(nums.indexOf(numSorted(i)), nums.indexOf(numSorted(j)))
}
}
}
return Array.empty
}它现在键入检查并运行OK。
scala> :load twoSum.scala
def twoSum(nums: Array[Int], target: Int): Array[Int]
scala> twoSum(Array(2,7,11,15), 9)
val res0: Array[Int] = Array(0, 1)https://stackoverflow.com/questions/71115561
复制相似问题