Skip to content

Commit e8290fd

Browse files
committed
src/bin/product-of-array-except-self.rs
1 parent 8102a0f commit e8290fd

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
fn main() {
2+
println!("{:?}", Solution::product_except_self(vec![1, 2, 3, 4]));
3+
}
4+
5+
struct Solution;
6+
7+
impl Solution {
8+
/// 常规解法
9+
pub fn product_except_self1(nums: Vec<i32>) -> Vec<i32> {
10+
let sum = nums.iter().fold(1, |x, y| x * *y);
11+
12+
nums.iter().fold(vec![], |mut x, y| {
13+
x.push(sum / (*y));
14+
x
15+
})
16+
}
17+
18+
/// 左右乘积,某个位置的积 == 左边*右边
19+
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
20+
let mut v = Vec::with_capacity(nums.len());
21+
for i in 0..nums.len() {
22+
if i == 0 {
23+
v.push(1);
24+
} else if i == 1 {
25+
v.push(nums[i - 1]);
26+
} else {
27+
v.push(nums[i - 1] * v[i - 1]);
28+
}
29+
}
30+
31+
let mut x = 1;
32+
33+
for i in (0..nums.len()).rev() {
34+
if i == nums.len() - 1 {
35+
x = nums[i];
36+
continue;
37+
} else {
38+
v[i] = v[i] * x;
39+
x *= nums[i];
40+
}
41+
}
42+
43+
v
44+
}
45+
}

0 commit comments

Comments
 (0)