【Leetcode】413. Arithmetic Slices

Subject address:

https://leetcode.com/problems/arithmetic-slices/

Given a length nnn arrayAAA , ask how many lengths are greater than or equal to3 3The sub-array of 3 happens to be an arithmetic sequence.

Any arithmetic array can expand the left and right endpoints to both sides as much as possible to form a longer arithmetic array, a long kkk arithmetic array (according to the requirement of the titlek ≥ 3 k\ge 3k3 ), which have(1 + k − 2) (k − 2) 2 \frac{(1+k-2)(k-2)}{2}2(1+k2)(k2)An arithmetic sub-array (including itself). So we just need to add AAA is regarded as the splicing of extremely large arithmetic arrays, and the length of each extremely arithmetic array is calculated and then accumulated according to the above formula. code show as below:

public class Solution {
    
    
    public int numberOfArithmeticSlices(int[] A) {
    
    
        int res = 0;
        // 枚举极大等差子数组的左端点
        for (int i = 0; i < A.length; i++) {
    
    
        	// 求其右端点
            int j = i + 1;
            while (j < A.length && A[i + 1] - A[i] == A[j] - A[j - 1]) {
    
    
                j++;
            }
            
            // 求得极大等差子数组的长度,如果长度大于等于3就累加
            int len = j - i;
            if (len >= 3) {
    
    
                res += (1 + len - 2) * (len - 2) / 2;
                i = j - 1;
            }
        }
        
        return res;
    }
}

Time complexity O (n) O(n)O ( n ) , spaceO (1) O (1)O ( 1 )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/112603177