mirror of
https://github.com/Xevion/leetcode.git
synced 2025-12-06 05:15:30 -06:00
Rust: product-of-array-except-self
This commit is contained in:
20
product-of-array-except-self/.gitignore
vendored
Normal file
20
product-of-array-except-self/.gitignore
vendored
Normal 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
|
||||
8
product-of-array-except-self/Cargo.toml
Normal file
8
product-of-array-except-self/Cargo.toml
Normal 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]
|
||||
34
product-of-array-except-self/src/main.rs
Normal file
34
product-of-array-except-self/src/main.rs
Normal 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]
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user