Skip to content

Instantly share code, notes, and snippets.

@renanreismartins
Created February 21, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renanreismartins/fde6f1de24ae38b0262ed244993e2fc9 to your computer and use it in GitHub Desktop.
Save renanreismartins/fde6f1de24ae38b0262ed244993e2fc9 to your computer and use it in GitHub Desktop.
Procedural approach
object MissingPositive extends App {
def missingPositive(nums: Array[Int]): Int = {
//val m1: Map[Int, Int] = (0 until nums.length).foldLeft(Map[Int, Int]())((m, i) => if (nums(i) > 0) m + (i -> 1) else m)
val found = scala.collection.mutable.Map[Int, Int]()
var min = Integer.MAX_VALUE
for (n <- nums) {
if (n >= 0) {
found += (n -> 1)
if (n < min) min = n
}
}
if (min >= 0) {
var count = 1
while (found.contains(count)) {
count += 1
}
count
} else {
min - 1
}
}
println(missingPositive(Array(1, 2, 0)))
println(missingPositive(Array(3, 4, -1, 1)))
println(missingPositive(Array(7, 8, 9, 11, 12)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment