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 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.

思路:题目很冗长,实际上就是找有几个等差数列(长度大于3的).i作为序列头,从0开始到N-3遍历数组,首先找一个最短的等差序列(长度为3),找到后算出间距dist,再以j为序列尾,从i+3开始到N向后扩张,看等差序列是否还存在后续.只要找到一个间距不等于dist,表明在这里断开,退出内层j循环,序列头后移一位.如此往复

int numberOfArithmeticSlices(vector<int>& A) {
    int N = A.size();
    int count = 0;
    if (N < 3) return 0; //特殊情况处理
    for (int i = 0; i < N-2; i++) { //遍历0到N-3的位置
        if (A[i+1] - A[i] != A[i+2] - A[i+1]) continue;  //A[i,i+1,i+2]不满足等差数列,直接跳过本次循环
        int dist = A[i+1] - A[i];  //等差间距distance
        count++;  //找到一个等差
        for (int j = i+3; j < N; j++) {  //j从i+2之后找,看等差序列是否还存在后续
            if (A[j] - A[j-1] != dist) break;  //只要发现一个不等的,立即退出循环
            count++;
        }
    }
    return count;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 陈道明帅吗? 帅! 必须帅! 年过60,却越来越帅! 最近热播的《我的前半生》,陈道明扮演其中的日料店“酱子”老板...
    小瑜姑娘阅读 4,371评论 6 15
  • url与资源 本章我们将介绍以下内容: url语法,以及各种url组件的含义及其所做的工作; 很多web客户端都支...
    shenyifu阅读 3,222评论 0 0
  • 虚拟现实的崛起已是必然,但任何一个对虚拟现实行业稍有了解的人,都应该了解,现阶段虚拟现实行业的发展,内容的发展是滞...
    小太阳会发光诺阅读 4,413评论 0 1
  • 但不是全部的科学家都这样认为。比如,麻省理工学院大气科学教授RL坚持说,全球变暖的说法是对"警告感兴趣"的人们...
    sxrunn阅读 1,326评论 0 1