LeetCode413. 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, 97, 7, 7, 73, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting 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 is called arithmetic if the sequence:A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the 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.

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int res=0,ss=0;
        for(int i=2;i<A.size();i++){
            if(A[i-1]-A[i-2]==A[i]-A[i-1]){
                res += ++ss;
            }else{
                ss=0;
            }
        }
        return res;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,093评论 0 23
  • 《雅舍谈吃》里梁实秋写腊肉那篇,有句话我是很赞同的:“湖南腊肉最出名,可是到了湖南却不能求之于店肆,真正上好的湖南...
    阿夏丽阅读 891评论 4 7
  • 最后的一次小聚会,周 高和我。
    假装没想到阅读 214评论 0 1
  • 从大二开始到现在,一直有朋友同学亲戚问我为什么吃这么多还这么瘦。是的,和我亲近的人都知道我爱吃,巧克力果冻薯片,...
    文艺女青年Sara阅读 443评论 3 4
  • 第三章 江湖一隅思故人(2) 桌下的兔子猛然抽搐了一下,立起耳朵,撒丫子往楼梯口蹿去,扭动着浑圆的身体又迟迟不敢往...
    丸子苏灿阅读 237评论 1 1