Leetcode 413. Arithmetic Slices

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Arithmetic Slices

2. Solution

解析:Version 1,计算每一数与其前一个数字的差,当有三个数且其连续差相等时构成一个算术(等差)数组,数字个数每加1子数组数量对应加1,不符合算术数组的元素一定不位于算术子数组中。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
n = len(nums)
count = 0
diff = 0
pre = 10000
temp = 0
for i in range(1, n):
diff = nums[i] - nums[i-1]
if diff == pre:
temp += 1
count += temp
else:
temp = 0
pre = diff
return count

Reference

  1. https://leetcode.com/problems/arithmetic-slices/
如果有收获,可以请我喝杯咖啡!