Skip to content

Commit 8c2738c

Browse files
committedJun 15, 2024
feat: 🎸 add leetcode solution 1. 49. 128. 217 238. 242
1 parent 892bdf8 commit 8c2738c

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed
 
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
struct Solution;
2+
3+
impl Solution {
4+
pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
5+
//preProduct * sufProduct
6+
// O(n)+O(n)
7+
let mut product = 1;
8+
let mut re_vec = vec![1;nums.len()];
9+
//get every item preProduct
10+
//before [1,2,3,4] return [1,1,1,1]
11+
//1. i=0 product = 1*1 return [1,1*1,1,1]
12+
//2. i=1 product = 1*2 return [1,1,1*2,1]
13+
//3. i=2 product = 2*3 return [1,1,2,1*6]
14+
//after [1,2,3,4] return [1,1,2,6]
15+
for i in 0..nums.len()-1{
16+
product=product*nums[i];
17+
re_vec[i+1]=product;
18+
}
19+
//get every item sufProduct
20+
//before [1,2,3,4] return [1,1,2,6]
21+
//1. i=3 product = 1*4 return [1,1,2*4,6]
22+
//2. i=2 product = 4*3 return [1,1*12,8,6]
23+
//3. i=1 product = 12*1 return [1*24,12,8,6]
24+
//after [1,2,3,4] return [24,12,8,6]
25+
product = 1;
26+
for i in (1..nums.len()).rev(){
27+
product = product*nums[i];
28+
re_vec[i-1] = product*re_vec[i-1];
29+
}
30+
re_vec
31+
}
32+
}
33+
34+
fn main() {
35+
let nums = vec![1, 2, 3, 4];
36+
let result = Solution::product_except_self(nums);
37+
println!("Product except self: {:?}", result);
38+
}
39+
40+
#[cfg(test)]
41+
mod tests {
42+
use super::*;
43+
44+
#[test]
45+
fn test_product_except_self() {
46+
assert_eq!(Solution::product_except_self(vec![1, 2, 3, 4]), vec![24, 12, 8, 6]);
47+
assert_eq!(Solution::product_except_self(vec![4, 3, 2, 1]), vec![6, 8, 12, 24]);
48+
assert_eq!(Solution::product_except_self(vec![2, 3, 4, 5]), vec![60, 40, 30, 24]);
49+
assert_eq!(Solution::product_except_self(vec![1, 2]), vec![2, 1]);
50+
assert_eq!(Solution::product_except_self(vec![10, 3, 5, 6, 2]), vec![180, 600, 360, 300, 900]);
51+
}
52+
}
Binary file not shown.

0 commit comments

Comments
 (0)