LeetCode Brush Questions (1) - Arithmetic Sequence Division

topic:

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 numbers are arithmetic progressions:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following numbers are not arithmetic progressions.

1, 1, 2, 5, 7

 

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 an arithmetic array if the following conditions are met:

The elements A[P], A[p + 1], ..., A[Q - 1], A[Q] are arithmetic differences. 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].


analyze:

Assuming that the length of array A is N+1, the number of arithmetic difference arrays contained in array A is count, starting from A[0], if A[1] - A[0] = A[2] - A[1] , then A[0], A[1], A[2] is an arithmetic array, count = 1. If A[1] - A[0] = A[2]- A[1] = A[3] - A[2] , then A [0], A[1], A[2], A[3 ] is another arithmetic array, count = 2; if A[1] - A[0] = A[2]- A[1]  A[3] - A[2] , then A [0], A [1], A[2], A[3] cannot form an arithmetic sequence, the traversal of A[0] ends here, and the traversal of A[1] begins. That is to say, as long as the traversal of A[i] fails to form an arithmetic array, the traversal of A[i] is ended, and the traversal of A[i + 1] is performed until i = N - 2. Below is the Java code:
class Solution {
    public int numberOfArithmeticSlices(int[] A) {
        int count = 0;
        if(A.length<3){
            return 0;
        }
        for(int i=0; i<A.length-2; i++){
            for(int j=i+1; j<A.length-1; j++){
                if(A[j + 1] - A[j] == A[i + 1] -A[i]){
                    count++;
                }else{
                    break;
                }
            }
        }
        return count;
    }
}


Guess you like

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