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:

<pre>1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9</pre>

The following sequence is not arithmetic.

<pre>1, 1, 2, 5, 7</pre>

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:
<pre>
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.
</pre>
其实这题没怎么读明白,大概的意思就是问这一串数里头包含多少个等差数列,最短的是三个成一个等差数列。
<pre>
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]
</pre>
这个有规律,按数列元素个数分,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<int>& A) {
        int res = 0;
        int add = 0; //这个数与前头形成等差数列,会增加几个等差数列。
        for(int i = 2;i<A.size();i++)
        {
            if(A[i-1]-A[i-2] == A[i]-A[i-1])
            {
                add++;  
                res += add;
            }
            else
                add = 0;
        }
        return res;   
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,421评论 0 23
  • 转载:互联网产品经理面试二三事(部分内容/整理) 1、时 间:6个月 阶 段:入行期 工作内容:产品策...
    东没米星客阅读 2,087评论 0 3
  • 懂得放下不是不做事,而是从内心要放下,从内心不要去执着,不要去担忧,才是放下。成都文殊院有一副对联的上联:...
    Lc林川阅读 1,202评论 1 2
  • #写在前面(原来没有写TT) 文章是根据真实事件改编而成,之后故事会出现虚拟人名,大家尽情期待(′`〃) 初中生文...
    久殇阅读 3,118评论 2 7
  • 世界让你疯狂,但是你不能疯狂 别跳起来揍它一拳 站着,冷冷的盯着它
    johnnywaiting阅读 1,144评论 0 1