From 1a6acb08d66ccca616dcda5a40ccf17ed35b8e93 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 15 Apr 2024 10:29:11 +0800 Subject: [PATCH] 20240415 Finished --- src/problem/mod.rs | 3 +- .../p238_product_of_array_except_self.rs | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 src/problem/p238_product_of_array_except_self.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 7b89966..cf17ae0 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -102,4 +102,5 @@ mod p122_best_time_to_buy_and_sell_stock_ii; mod p55_jump_game; mod p45_jump_game_ii; mod p274_h_index; -mod p380_insert_delete_getrandom_o1; \ No newline at end of file +mod p380_insert_delete_getrandom_o1; +mod p238_product_of_array_except_self; \ No newline at end of file diff --git a/src/problem/p238_product_of_array_except_self.rs b/src/problem/p238_product_of_array_except_self.rs new file mode 100644 index 0000000..a0aa24d --- /dev/null +++ b/src/problem/p238_product_of_array_except_self.rs @@ -0,0 +1,45 @@ +/** + * [238] Product of Array Except Self + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn product_except_self(nums: Vec) -> Vec { + let mut result = vec![1; nums.len()]; + + for i in 1..nums.len() { + result[i] = result[i - 1] * nums[i - 1]; + } + + let mut suffix = 1; + + for i in (0..nums.len() - 1).rev() { + suffix *= nums[i + 1]; + + result[i] *= suffix; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_238() { + assert_eq!( + vec![24, 12, 8, 6], + Solution::product_except_self(vec![1, 2, 3, 4]) + ); + assert_eq!( + vec![0, 0, 9, 0, 0], + Solution::product_except_self(vec![-1, 1, 0, -3, 3]) + ); + } +}