Leetcode 413. Arithmetic Slices

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

1. Description

Arithmetic Slices

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

Reference

  1. https://leetcode.com/problems/arithmetic-slices/

你可能感兴趣的:(Leetcode 413. Arithmetic Slices)