leet-code/first-missing-positive/sol.rs

37 lines
1.3 KiB
Rust
Raw Permalink Normal View History

2022-05-29 19:21:38 +00:00
struct Solution {}
2022-06-12 11:43:26 +00:00
// TODO: Incomplete
2022-05-29 19:21:38 +00:00
impl Solution {
pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
2022-06-12 11:43:26 +00:00
let (count, max, sum) = nums
2022-05-29 19:21:38 +00:00
.iter()
2022-06-12 11:43:26 +00:00
.fold((0, 0, 0), |(count, max, sum), n| {
2022-05-29 19:21:38 +00:00
if *n > 0 {
2022-06-12 11:43:26 +00:00
return (count + 1, if *n > max { *n } else { max }, sum + *n);
2022-05-29 19:21:38 +00:00
}
2022-06-12 11:43:26 +00:00
(count, max, sum)
2022-05-29 19:21:38 +00:00
});
2022-06-12 11:43:26 +00:00
let expected_sum = max * (max + 1) / 2;
let missing = max - count;
let diff = expected_sum - sum;
if diff == 0 {
max + 1
} else if missing == 1 {
diff
} else {
let min_k = missing * (missing - 1) / 2;
(1..).find(|&n| {
let k = diff - n * missing;
k >= min_k && n + k - min_k + missing <= max
}).unwrap()
}
2022-05-29 19:21:38 +00:00
}
}
fn main() {
2022-06-12 11:43:26 +00:00
println!("{}", Solution::first_missing_positive(vec![7,9,10])); // n = 1, m = 7, k = 22
println!("{}", Solution::first_missing_positive(vec![6,5,-1,2,4,3,1])); // n = 7, m = 1, k = 0
println!("{}", Solution::first_missing_positive(vec![4,-1,1])); // n = 2, m = 2, k = 1
println!("{}", Solution::first_missing_positive(vec![4,6,-1,1])); // n = 2, m = 3, k = 4
println!("{}", Solution::first_missing_positive(vec![2,2])); // n = 2, m = 3, k = 4
2022-05-29 19:21:38 +00:00
}