- Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproduct-of-array-except-self.rs
47 lines (39 loc) · 1.09 KB
/
product-of-array-except-self.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#![allow(dead_code, unused, unused_variables)]
fnmain(){
println!("{:?}",Solution::product_except_self(vec![1,2,3,4]));
}
structSolution;
implSolution{
/// 常规解法
pubfnproduct_except_self1(nums:Vec<i32>) -> Vec<i32>{
let sum = nums.iter().fold(1, |x, y| x **y);
nums.iter().fold(vec![], |mut x, y| {
x.push(sum / (*y));
x
})
}
/// 左右乘积,某个位置的积 == 左边*右边
pubfnproduct_except_self(nums:Vec<i32>) -> Vec<i32>{
letmut v = Vec::with_capacity(nums.len());
for i in0..nums.len(){
if i == 0{
v.push(1);
}elseif i == 1{
v.push(nums[i - 1]);
}else{
v.push(nums[i - 1]* v[i - 1]);
}
}
letmut x = 1;
for i in(0..nums.len()).rev(){
if i == nums.len() - 1{
x = nums[i];
continue;
}else{
v[i] = v[i]* x;
x *= nums[i];
}
}
v
}
}