这通常发生在我使用会改变数组或列表的东西时。例如这里:nums.drop(i)。我尝试调试,但它甚至没有看到该行,如果您向我解释这种行为,我将不胜感激
def findDuplicates(nums: Array[Int]): List[Int] = {
nums.foldLeft(0)((accumValue, nextEl) => {
if (nums.tail.contains(nextEl)) {
accumValue
} else {
nums.drop(accumValue)
accumValue
}
})
nums.toList
}
方法
drop
不会将元素放置到位。它返回一个新数组,其中没有删除的元素。而且你不以任何方式使用这个新数组(你不将这个值分配给一些val
等),你只是忽略结果。
/** The rest of the array without its `n` first elements. */
def drop(n: Int): Array[A] = ...
https://github.com/scala/scala/blob/v2.13.10/src/library/scala/collection/ArrayOps.scala#L374
不是
def drop(n: Int): Unit
.