文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
解析:Version 1,计算每一数与其前一个数字的差,当有三个数且其连续差相等时构成一个算术(等差)数组,数字个数每加1
子数组数量对应加1
,不符合算术数组的元素一定不位于算术子数组中。
- Version 1
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