413. Arithmetic Slices

来源:互联网 发布:粒子群算法工具箱 编辑:程序博客网 时间:2024/06/05 02:47
class Solution(object):
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        opt, i = [0,0], 1
        for j in xrange(2,len(A)):
            if A[j]-A[j-1] == A[j-1]-A[j-2]:
                opt.append(opt[j-1]+i)
                i += 1
            else:
                opt.append(opt[j-1])
                i = 1

        return opt[-1]

求至少3连续元素等差的个数

https://leetcode.com/problems/arithmetic-slices/#/solutions


class Solution(object):
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        cur, sums = 0, 0
        for j in xrange(2,len(A)):
            if A[j]-A[j-1] == A[j-1]-A[j-2]:
                cur += 1
                sums +=cur
            else:
                cur = 0
        return sums
                

原创粉丝点击