arrays - Looking for an element in the array scala
问题描述
I'm writing this function in order to identify the first missing element from the array. I want to return the missing element but I'm getting a Unit
I can't identify what am I missing
def missingElement(a : Array[Int]) : Int = {
val result =for (i <- 1 to a.length) {
if(! a.contains(i)) {
i
}
}
result
}
解决方案
"identify the first" is a find
operation, so the code might look like this:
def missingElement(a: Array[Int]): Option[Int] =
a.indices.find(i => !a.contains(i+1))
This returns an Option
because there might not be a missing element, in which case it will return None
, otherwise it will return Some(n)
.
推荐阅读
- php - 如何解析 Facebook 提要并在网站上显示
- python - 如何在熊猫中相互减去两列列表?
- reactjs - React LocalForm 不调用 onUpdate
- python - 如何根据网络字符串列表设置多种颜色?
- python - 如何更改 pipenv/virtualenv 位置以使用便携式 VS 代码和拇指驱动器上的项目?
- python - discord.py 如何每天在特定时间发送消息
- vba - 如何使用VBA一次更改多个图形中XY轴和格式的相同标题?
- arrays - 替换嵌套在数组中的 Hash 的键值
- node.js - NodeJs - 一起编写异步和非异步函数
- c++11 - std::stirng 的对象生命周期返回 const char* 作为返回值