Skip to content

Commit f4f0840

Browse files
committed
src/bin/arithmetic-slices.rs
1 parent b2f5983 commit f4f0840

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/bin/arithmetic-slices.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
fn main() {
2+
println!("{}", Solution::number_of_arithmetic_slices(vec![1, 2, 3, 4]));
3+
println!("{}", Solution::number_of_arithmetic_slices(vec![1, 2, 3, 4, 5, 6]));
4+
println!("{}", Solution::number_of_arithmetic_slices(vec![1, 2, 3, 4, 10, 11, 12, 13]));
5+
}
6+
7+
struct Solution;
8+
9+
impl Solution {
10+
pub fn number_of_arithmetic_slices(nums: Vec<i32>) -> i32 {
11+
if nums.len() < 3 { return 0; }
12+
13+
let mut count = 0;
14+
let mut num = 2;
15+
let mut s = nums[1] - nums[0];
16+
17+
for i in 2..nums.len() {
18+
if nums[i] - nums[i - 1] == s {
19+
num += 1;
20+
} else {
21+
if num >= 3 { count += (1..=num - 3 + 1).into_iter().sum::<i32>(); }
22+
s = nums[i] - nums[i - 1];
23+
num = 2;
24+
}
25+
}
26+
27+
if num >= 3 { count += (1..=num - 3 + 1).into_iter().sum::<i32>(); }
28+
29+
count
30+
}
31+
}

0 commit comments

Comments
 (0)