add "product of array except self" in rust

This commit is contained in:
Joe Ardent 2023-11-02 17:41:09 -07:00
parent db142ff1df
commit 34db36cf0b
2 changed files with 65 additions and 0 deletions

View file

@ -0,0 +1,8 @@
[package]
name = "product_of_array_except_self"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,57 @@
struct Solution;
enum Zeros {
None,
One(usize),
Many,
}
impl Solution {
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let mut out = vec![0i32; nums.len()];
let nums = nums.as_slice();
let zeros = count_zeros(nums);
match zeros {
Zeros::None => {
let prod: i32 = nums.iter().product();
for (i, x) in nums.iter().enumerate() {
out[i] = prod / x;
}
}
Zeros::One(z) => {
let left = if z == 0 {
1
} else {
nums[0..z].iter().product()
};
let right = if z == nums.len() - 1 {
1
} else {
nums[(z + 1)..].iter().product()
};
out[z] = left * right;
}
_ => {}
}
out
}
}
fn count_zeros(nums: &[i32]) -> Zeros {
let mut zeros = std::collections::HashSet::new();
for (i, n) in nums.iter().enumerate() {
if *n == 0i32 {
zeros.insert(i);
}
}
match zeros.len() {
0 => Zeros::None,
1 => Zeros::One(*zeros.iter().next().unwrap()),
_ => Zeros::Many,
}
}
fn main() {
println!("Hello, world!");
}