-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsum_of_all_odd_length_subarrays.rs
62 lines (57 loc) · 1.71 KB
/
sum_of_all_odd_length_subarrays.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*!
请你计算所有可能的奇数长度子数组的和。
输入:arr = [1,4,2,5,3]
输出:58
解释:所有奇数长度子数组和它们的和为:
\[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
*/
struct Solution;
impl Solution {
fn sum_odd_length_subarrays(nums: Vec<i32>) -> i32 {
let n = nums.len();
let mut total_sum = 0;
let mut window_len = 1;
while window_len <= n {
let (mut left, mut right) = (0, window_len);
let mut window_sum = (0..window_len).map(|i| nums[i]).sum::<i32>();
total_sum += window_sum;
while right < n {
window_sum += nums[right] - nums[left];
total_sum += window_sum;
left += 1;
right += 1;
}
window_len += 2;
}
total_sum
}
/// 如果能用Itertools::tuple_windows的话,会比windows方便很多,可以实现`for (a, b) in nums.iter().tuple_windows的话(2)`
fn solution_use_slice_windows_api(nums: Vec<i32>) -> i32 {
(1..=nums.len())
.step_by(2)
.map(|window_len| {
nums.windows(window_len)
.map(|window| window.iter().sum::<i32>())
.sum::<i32>()
})
.sum()
}
}
#[cfg(test)]
const TEST_CASES: [(&[i32], i32); 1] = [(&[1, 4, 2, 5, 3], 58)];
#[test]
fn test() {
for &(nums, sum) in &TEST_CASES {
assert_eq!(Solution::sum_odd_length_subarrays(nums.to_vec()), sum);
assert_eq!(Solution::solution_use_slice_windows_api(nums.to_vec()), sum);
}
}