413 Arithmetic Slices

If a sequence has at least three elements and the difference between any two adjacent elements is the same, the sequence is called an arithmetic sequence.
For example, the following sequence is an arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not an arithmetic sequence.
1, 1, 2, 5, 7
The array A contains N numbers, and the index starts from 0. A subarray of array A is divided into arrays (P, Q), where P and Q are integers and satisfy 0<=P<Q<N.
A subarray (P, Q) is said to be arithmetic if the following conditions are met:
elements A[P], A[p + 1], ..., A[Q - 1], A[Q] are arithmetic of. and P + 1 < Q .
The function wants to return the number of all subarrays in array A that are arithmetic arrays.
Example:
A = [1, 2, 3, 4]
Returns: 3, A has three subarithmetic arrays: [1, 2, 3], [2, 3, 4] and itself [1, 2, 3, 4 ].
See: https://leetcode.com/problems/arithmetic-slices/description/

C++:

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

 Reference: https://www.cnblogs.com/grandyang/p/5968340.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324459431&siteId=291194637