LeetCode 413. Arithmetic Slices [Medium]

原题地址

题目内容

这里写图片描述

题目分析

A[i]-A[i+1] = A[i+1]-A[i+2],这样的式子成为arithmetic,也就是等差数列,题目的意思为,给你一个数组,问最多能分为多少个等差数列,每个数列至少含有3个数字。
一开始想用动态规划的方法,但后面发现暴力求解也挺简单的,就过了。对于每一个A[i]都求出从i开头能分割多少组等差数列出来,然后tot++,一旦不行就从i+1开始继续分,最后返回tot即可。

代码实现

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

    }
};

猜你喜欢

转载自blog.csdn.net/YuMingJing_/article/details/78719927