首页 > 解决方案 > 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

}

标签: arraysscalamissing-data

解决方案


"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).


推荐阅读