Leetcode 413. Arithmetic Slices

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-413-Arithmetic Slices]

413. Arithmetic Slices(LeetCode)

Leetcode413. Arithmetic Slices

leetcode 413. Arithmetic Slices 等差数列划分

[leetcode]Math-413. Arithmetic Slices

(Java) LeetCode 413. Arithmetic Slices —— 等差数列划分