你能用我的解决方案让我停下来吗。我写了一些方法它得到了一些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: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
复制相似问题