leetcode 413. Arithmetic Slices

A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequence:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.

1, 1, 2, 5, 7
一道中等难度的题目
题意是说能数组中含有多少连续的等差序列,最简单的方法是列出所有的序列,装入数组中,最后返回数组的长度,但这样时间极久。我们想,我们其实没必要每次都重复计算新的序列是不是等差序列,假设已经计算过A[1],A[2],A[3]为等差序列,那么在计算A[1],A[2],A[3],A[4]是否为等差序列的时候,只需要在之前计算的结果上,用A[4]-A[3]看看是否等于前面的等差dif,是则装入结果,否则continue。这样我们省去了重复计算的部分,但是仍然需要维持一个二维数组来记录已满足的等差序列,空间复杂度仍然是O(N^2),可以考虑,其实判断新添加的元素能否和过去的序列组成新的等差序列,只需要用一个pair结构,维持一个dif,和之前等差序列的最后一个元素index就行了,每次判断新元素是否合理的时候,只需要判断A[index+1]-A[index]==dif即可,如果满足,更新此pair,这样只需要O(N)的空间复杂度即可,代码如下:
0ms

int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size()<3)
            return 0;
        vector<pair<int,int>>work;
        for(int i=0;i<A.size()-2;++i){
            int dif=A[i+1]-A[i];
            work.push_back({i+1,dif});
        }
        int res=0;
        while(!work.empty()){
            int k=0;
            vector<pair<int,int>>next;
            while(k<work.size()){
                int pos=work[k].first;
                int dif=work[k].second;
                if(pos+1<A.size() && A[pos+1]-A[pos]==dif){
                    ++res;
                    next.push_back({pos+1,dif});
                }
                ++k;
            }
            swap(work,next);
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值