413. Arithmetic Slices

原题如下:

413.Arithmetic Slices

Asequence of number is called arithmetic if it consists of at least threeelements and if the difference between any two consecutive elements is thesame.

For example, these arearithmetic sequence:

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

The following sequence is notarithmetic.

1, 1, 2, 5, 7

 

A zero-indexed array Aconsisting of N numbers is given. A slice of that array is any pair of integers(P, Q) such that 0 <= P < Q < N.

A slice (P, Q) of array A iscalled arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this meansthat P + 1 < Q.

The function should returnthe number of arithmetic slices in the array A.

 

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.

题目大意:给定一个数组,找到题目中所有的长度大于等于3的等差子数列的数目。

解题思路:这道题目也是比较简单的,不知道为什么算medium难度的题,先求出数组n个元素两两之间的差值存到一个差值数组中,然后找出连续相等的差值的长度count,构建一个长度为n-1的结果数组res,那么根据count的值可以求出res[i]的值,若count=0,说明差值数组暂时没有两个连续相同的数,则res[i]=res[i-1]。若是count=1,说明差值数组中有两个是连续相等的,所以res[i]=res[i-1]+1,若是count>1,则res[i]=2*res[i-1]-res[i-2]+1。

算法:

input:A(数组)

output:res[n-2](n为)

 n=A.size();

        if(n<3)return 0;

 vector<int>diff=every difference between any two consecutive elementsof A;//差值数组

        vector<int> res(n-1,0);

        int count=0;

        for elements from 1 to n-2 in diff

            if(diff[i]==diff[i-1]){

                count++;

            }

            else

            count=0;

            if(count==1){

                res[i]=res[i-1]+1;

            }

            else if(count==0){

                res[i]=res[i-1];

            }

            else{

                res[i]=2*res[i-1]-res[i-2]+1;

            }

         res[n-2] is the final result.

算法复杂度分析:整个函数只用了一层循环解决问题,所以最坏复杂度为O(N),其中N是数组大小。

具体代码如下:

class Solution {

public:

    intnumberOfArithmeticSlices(vector<int>& A) {

        int n=A.size();

        if(n<3)return 0;

        vector<int> diff;

        vector<int> res(n-1,0);

        for(int i=0;i<n-1;i++){

            diff.push_back(A[i+1]-A[i]);

        }

        int count=0;

        for(int i=1;i<n-1;i++){

            if(diff[i]==diff[i-1]){

                count++;

            }

            else

            count=0;

            if(count==1){

                res[i]=res[i-1]+1;

            }

            else if(count==0){

                res[i]=res[i-1];

            }

            else{

                res[i]=2*res[i-1]-res[i-2]+1;

            }

        }

        return res[n-2];

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值