[Math_Medium]413. Arithmetic Slices

413. Arithmetic Slices

题目大意:找出数组中存在多少等差序列(该序列在原数组是连续的)

解题思路:

  • 1,2,3 → 存在一个即1,2,3
  • 1,2,3,4 →存在3个,即1,2,3;1,2,3,4; 2,3,4;在原来1,2,3的基础上多了2个
  • 1,2,3,4,5 → 存在6个,即1,2,3; 1,2,3,4; 2,3,4; 1,2,3,4,5; 2,3,4,5; 3,4,5;增加了3个
    。。。。。。。
    1,2,3,4,5....N: 存在 1+2+3+4+...+(N-3)个,所以只需要判断连续的等差序列有多少项,在直接计算即可。

源代码:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size()<3)
            return 0;
        int ans=0,temp=0;
        for(int i=0;i<A.size()-2;i++)
        {
            if((A[i+1]-A[i])==(A[i+2]-A[i+1]))
                temp++;
            else
            {
                ans+=((1+temp)*temp/2);
                temp=0;
            }
        }
        ans+=((1+temp)*temp/2);
        return ans;
    }
};

以上

posted @ 2018-08-21 21:35  默写年华  阅读(90)  评论(0编辑  收藏  举报