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