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

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.

其实这题没怎么读明白,大概的意思就是问这一串数里头包含多少个等差数列,最短的是三个成一个等差数列。

1,2,3// 1个 [1 2 3]
1,2,3,4// 3个 [1 2 3] [2 3 4] [1 2 3 4]
1,2,3,4,5//6个[1 2 3][2 3 4][3 4 5] [1 2 3 4][2 3 4 5] [1 2 3 4 5]

这个有规律,按数列元素个数分,N个数的等差数列有N-2 种,N+1个数的,相当于前N-2种每种比N个的多一个,再多加一个N+1个数的数列,相当于N+1的比N个数的多N-2+1个,即(N+1)-2个。
所以就循环,从头到尾数,可以组成几个最长的等差数列就好了。累加起来就是结果。
代码如下。

class Solution {
public:
    int numberOfArithmeticSlices(vector& A) {
        int res = 0;
        int add = 0; //这个数与前头形成等差数列,会增加几个等差数列。
        for(int i = 2;i

你可能感兴趣的:(413. Arithmetic Slices 笔记)