413. Arithmetic Slices(等差级数)

来源:互联网 发布:sat数学 知乎 编辑:程序博客网 时间:2024/06/18 07:12

标签(空格分隔): leetcode dp


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.

题意:
1. 数字序列如果由至少三个元素组成,并且任何两个连续元素之间的差异是相同的,则称为等差。
2. 等差数列如上面的例子;
3. 给出了由N个数字组成的零开始的索引数组A.,如果序列:A [P],A [p + 1],…,A [Q-1],A[Q]是等差运算;
4. 特别地,这意味着P+1<Q。该阵列的切片是任何一对整数(P,Q),使得0<=P<Q<N.数组A的切片(P,Q)称为等差数列;
5. 该函数应该返回数组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. 数列至少有3个数: p+1<q
2. [p+1] - [p] = [p+2]- [p+1]
3. 返回所有子序列为等差序列的数目

代码:

int numberOfArithmeticSlices(vector<int>& A) {    int len = A.size();    if (len < 3)  //小于三的长度,直接返回        return 0;    int totalsum = 0;    int sum = 2;//设在2的长度,只要下面比较相等,说明长度为三    for (int i = 2; i < len; ++i)    {        if ((A[i-1]-A[i-2])==(A[i]-A[i-1]))//至少三个相等,sum+1        {            sum++;        }        else if (!(sum<2))//遇到不是等差的数,并且长度大于等于3,先统计        {            for (int j = 1; j <sum - 1; ++j)                totalsum += j;            sum = 2; //非常重要,必须重新初始化        }    }    if (!(sum < 2)) //遇到等差数列结尾的情况,需要统计    {        for (int j = 1; j <sum - 1; ++j)            totalsum += j;    }    return totalsum;}

非常感谢下面文档的灵感!
【相关文档】
1.LeetCode 413.Arithmetic Slices 解题报告

原创粉丝点击