zoukankan      html  css  js  c++  java
  • [Math_Medium]413. Arithmetic Slices

    413. Arithmetic Slices

    题目大意:找出数组中存在多少等差序列(该序列在原数组是连续的)

    解题思路:

    • 1,2,3 → 存在一个即1,2,3
    • 1,2,3,4 →存在3个,即1,2,3;1,2,3,4; 2,3,4;在原来1,2,3的基础上多了2个
    • 1,2,3,4,5 → 存在6个,即1,2,3; 1,2,3,4; 2,3,4; 1,2,3,4,5; 2,3,4,5; 3,4,5;增加了3个
      。。。。。。。
      1,2,3,4,5....N: 存在 1+2+3+4+...+(N-3)个,所以只需要判断连续的等差序列有多少项,在直接计算即可。

    源代码:

    class Solution {
    public:
        int numberOfArithmeticSlices(vector<int>& A) {
            if(A.size()<3)
                return 0;
            int ans=0,temp=0;
            for(int i=0;i<A.size()-2;i++)
            {
                if((A[i+1]-A[i])==(A[i+2]-A[i+1]))
                    temp++;
                else
                {
                    ans+=((1+temp)*temp/2);
                    temp=0;
                }
            }
            ans+=((1+temp)*temp/2);
            return ans;
        }
    };
    

    以上

  • 相关阅读:
    Git Bash关键命令
    一个不需要Log4Net的写日志的简单方法
    未知软件
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
  • 原文地址:https://www.cnblogs.com/qiulinzhang/p/9514431.html
Copyright © 2011-2022 走看看