美文网首页Leetcode
Leetcode 413. Arithmetic Slices

Leetcode 413. Arithmetic Slices

作者: SnailTyan | 来源:发表于2021-08-11 09:40 被阅读0次

    文章作者: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

        本文链接:https://www.haomeiwen.com/subject/homjmltx.html