【LeetCode】413. Arithmetic Slices

来源:互联网 发布:单片机计分牌课设 编辑:程序博客网 时间:2024/06/06 06:44

题目:

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.


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.


题解:

题目可以理解为,找出已给序列的子序列,子序列的要求是不少于3个数字,且是等差数列。因为题目中说,A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic,所以不存在A[1]A[3]A[5]……这样的序列,即子序列中的数字在已给序列中是相邻的。令count[i]表示以A[i]结尾的子序列的个数,每次判断A[i]-A[i-1]是否等于A[i-1]-A[i-2],若相等,则count[i]=count[i-1]+1,因为A[i]是前面已判断出的子序列的扩展。最后把数组里所有数字相加,即是结果。


答案:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size()<3)
            return 0;
        if(A.size()==3)
            return 1;
        int count[A.size()];
        for(int i=0;i<A.size();i++)
            count[i]=0;
        if(A[2]-A[1]==A[1]-A[0])
            count[2]=1;
        for(int i=3;i<A.size();i++)
        {
            if(A[i]-A[i-1]==A[i-1]-A[i-2])
                count[i]=count[i-1]+1;
        }
        int result=0;
        for(int i=0;i<A.size();i++)
        {
            result+=count[i];
        }
        return result;
    }
};


0 0
原创粉丝点击