20240415 Finished

This commit is contained in:
jackfiled 2024-04-15 10:29:11 +08:00
parent d427e7c1d8
commit 1a6acb08d6
2 changed files with 47 additions and 1 deletions

View File

@ -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;
mod p380_insert_delete_getrandom_o1;
mod p238_product_of_array_except_self;

View File

@ -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<i32>) -> Vec<i32> {
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])
);
}
}