Created
February 21, 2023 15:48
-
-
Save renanreismartins/43efce7997518880e0f96594a2051633 to your computer and use it in GitHub Desktop.
A bit better, much to be done. Maybe do both operations in one traverse, fix the imperative checks and 0 checks. But enough for the day
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object MissingPositive extends App { | |
def missingPositive(nums: Array[Int]): Int = { | |
val found: Map[Int, Int] = nums.foldLeft(Map[Int, Int]())((m, i) => if (i >= 0) m + (i -> 1) else m) | |
val min = nums | |
.filter(e => e > 0) | |
.foldLeft(Integer.MAX_VALUE)((m, i) => i.min(m)) | |
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