rs: add «41. First Missing Positive»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-03-26 22:08:37 +01:00
parent 48d437c878
commit 5c3727b0d9
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,21 @@
impl Solution {
pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
let n = nums.len() + 1;
let mut seen = vec![false; n];
for x in nums.into_iter() {
if x <= 0 || (n as i32) <= x {
continue;
}
seen[x as usize - 1] = true;
}
1 + seen
.into_iter()
.enumerate()
.find(|(_, val)| !val)
.expect("there's always a missing positive integer")
.0 as i32
}
}