Rust: product-of-array-except-self

This commit is contained in:
2023-09-20 20:21:31 -05:00
parent 3497d4708f
commit 74af1bf7bc
3 changed files with 62 additions and 0 deletions

20
product-of-array-except-self/.gitignore vendored Normal file
View File

@@ -0,0 +1,20 @@
# Created by https://www.toptal.com/developers/gitignore/api/rust
# Edit at https://www.toptal.com/developers/gitignore?templates=rust
### Rust ###
# Generated by Cargo
# will have compiled files and executables
debug/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# End of https://www.toptal.com/developers/gitignore/api/rust

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,34 @@
struct Solution {}
impl Solution {
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let mut result = vec![1; nums.len()];
let mut left = 1;
let mut right = 1;
println!("{:?}", result);
for i in 0..nums.len() {
// Moving left to right: multiple each number by the preceding number
result[i] *= left;
left *= nums[i];
// Moving right to left, multiple each number by the following number
result[nums.len() - 1 - i] *= right;
right *= nums[nums.len() - 1 - i];
}
result
}
}
fn main() {
assert_eq!(
Solution::product_except_self(vec![1, 2, 3, 4]),
vec![24, 12, 8, 6]
);
assert_eq!(
Solution::product_except_self(vec![-1, 1, 0, -3, 3]),
vec![0, 0, 9, 0, 0]
)
}