[Leetcode Learning-c++&java]Arithmetic Slices

problem:

Difficulty: medium

Description:

Arithmetic array, input an array, and ask to find all non-repetitive arithmetic substrings (continuous subsequences) with length >= 3.

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

Enter the case:

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.

My code:

It took a week to understand that there are so many big brothers.

The continuous interval solution must be a sliding window , and the two traversal processing inside and outside will do, and the loop inside while.

Then because it is to find the substring with length >= 3, then in an arithmetic continuous sequence, the substring with length (size) >= 3 and not repeating:

Length 3: size-2

Length 4: size-3

..........

Length i: size-i + 1, which is equivalent to ΣN is a mathematical formula for adding an arithmetic array, only (i-1) * (i-2) >> 1 can be obtained in a continuous sequence The number of substrings (not repeating more than 3)

Java:

class Solution {
    public int numberOfArithmeticSlices(int[] A) {
            if(A.length < 3) return 0;
            int len = A.length, count = 0, temp = 2, dis = A[1] - A[0];
            boolean flag;
            for(int i = 2;i < len;) {
                flag = true;
                while(i < len && A[i] - A[i - 1] == dis) {
                    i ++; temp ++; flag = false;
                }
                if(!flag) count += (temp - 1) * (temp - 2) >> 1;
                if(i < len) {
                    dis = A[i] - A[i - 1]; temp = 2;
                }
                i ++;
            }
            return count;
        }
}

C++:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size() < 3) return 0;
        int len = A.size(), count = 0, size = 2, dis = A[1] - A[0], flag;
        for(int i = 2; i < len;) { // 从2开始
            flag = 0;
            while(i < len && A[i] - A[i - 1] == dis) {
                size ++; i ++; flag = 1;
            }
            if(flag) count += (size - 1) * (size - 2) >> 1;
            if(i < len) {
                dis = A[i] - A[i - 1]; size = 2; // 重置数据
            }
            i ++; // 必须要再加,否则下一次进来会经历同一个 i
        }
        return count;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/113849984