[LeetCode] 413. Arithmetic Slice

2018-07-20  本文已影响0人  TurtleLin

413. Arithmetic Slices

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, 9
7, 7, 7, 7
3, -1, -5, -9

即等差数列。

问题:
找出数组A中等差数列的个数,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.

思路:

  1. 长度为n的数组A为等差数列,在数组后面增加一个数,若数组最后一个数的两倍等于数组倒数第二个数加新数,则新数与数组A组成一个新的等差数列。
  2. 长度为n的数组A不是等差数列,则在数组面增加新数组成的新数组不可能是等差数列

Solution

class Solution:
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        n = len(A)
        count = 0
        available = list(range(1, n))

        while True:
            new_available = []
            for i in available:
                if i < n - 1 and A[i + 1] + A[i - 1] == 2 * A[i]:
                    new_available.append(i+1)
                    count += 1
            available = new_available
            if len(available) == 0:
                break
        return count
上一篇下一篇

猜你喜欢

热点阅读