413. Arithmetic Slices | LeetCode Dynamic Programming

来源:互联网 发布:京东人工智能 编辑:程序博客网 时间:2024/06/09 14:03

Description

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.

Thinking

这题的要求是在给出的一串数字中找到等差子数列的个数,且子数列包含至少三个元素。很简单,用一次for循环扫描整个数列,设置两个变量count和add,count表示符合要求的子数列总数,add表示当前增加的等差子数列个数。
当扫描到的第i个元素符合A[i + 1] - A[i] == A[i + 1] - A[i + 2]时,add加一,等差子数列总数又增加add个;当第i个元素A[i]不符合这一规律时,将add重置为0,重新开始计数。这是通过简单列举发现的规律。

Solution

class Solution {public:    int numberOfArithmeticSlices(vector<int>& A) {        int size = A.size();        if(size < 3) return 0;        int count = 0;        int add = 0;        for(int i = 0; i < size - 2; i++){            int t1 = A[i + 1] - A[i];            int t2 = A[i + 2] - A[i + 1];            if(t1 == t2){                add++;                count += add;            }            else add = 0;        }        return count;    }};
0 0
原创粉丝点击