reuse array for product

This commit is contained in:
Joe Ardent 2023-11-02 22:25:39 -07:00
parent 34db36cf0b
commit 06b15921fd

View file

@ -8,29 +8,29 @@ enum Zeros {
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 mut out = nums;
let nums = &mut out;
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;
for x in nums.iter_mut() {
*x = prod / *x;
}
}
Zeros::One(z) => {
let left = if z == 0 {
1
} else {
nums[0..z].iter().product()
};
let (left, right) = nums.split_at(z);
let left = if z == 0 { 1 } else { left.iter().product() };
let right = if z == nums.len() - 1 {
1
} else {
nums[(z + 1)..].iter().product()
right[1..].iter().product()
};
out[z] = left * right;
for x in nums.iter_mut() {
*x = 0;
}
nums[z] = left * right;
}
_ => {}
}
@ -39,19 +39,22 @@ impl Solution {
}
fn count_zeros(nums: &[i32]) -> Zeros {
let mut zeros = std::collections::HashSet::new();
let mut out = Zeros::None;
let zs = 0;
for (i, n) in nums.iter().enumerate() {
if *n == 0i32 {
zeros.insert(i);
if zs == 0 {
out = Zeros::One(i);
} else {
out = Zeros::Many;
break;
}
}
match zeros.len() {
0 => Zeros::None,
1 => Zeros::One(*zeros.iter().next().unwrap()),
_ => Zeros::Many,
}
out
}
fn main() {
println!("Hello, world!");
let p = Solution::product_except_self(vec![-1, 1, 0, -3, 3]);
dbg!(p);
}