leetcode_413. Arithmetic Slices 数组中连续的等差数列个数

来源:互联网 发布:微课录屏制作软件 编辑:程序博客网 时间:2024/06/13 06:27

题目:

A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequence:

1, 3, 5, 7, 97, 7, 7, 73, -1, -5, -9

The following sequence is not arithmetic.

1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.

A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.

The function should return the number of arithmetic slices in the array A.


Example:

A = [1, 2, 3, 4]return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.

题意:

给定数组A,求A中长度至少为3,且位置连续的等差数列的个数


代码:

class Solution(object):
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        
        n = len(A)
        
        if n < 3 :
            return 0
        else :
            res = 0      #记录等差数列个数
            add = 0      #记录在原来等差数列基础上增加一个元素形成新的等差数列后,原来的等差数列个数需要增加的数目
            
            for i in range(2,n) :
                if A[i]-A[i-1] == A[i-1]-A[i-2] :
                    add += 1
                    res += add      #在原来的基础上,增加元素后等差数列总数需要增加的数目
                else :
                    add = 0
            return res
        

笔记:

参考了两个大神的思路:

http://www.bubuko.com/infodetail-1800825.html

http://blog.csdn.net/camellhf/article/details/52824234

0 0
原创粉丝点击