Leetcode刷题总结: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.

题解:

思路一:用一个二维数组isArith记录从i到j是否为一个arithmetic sequence,时间复杂度和空间复杂都是O(n2)

思路二:用一个一维数组isArith记录以i为起始到end为终止,一共有几个arithmetic sequence,时间复杂度是O(n2), 空间复杂度是O(n)

思路三:用一个数组diff记录相邻两个元素的差值,从i开始遍历,找到第一个diff[i-1]==diff[i],表示找到了一个arithmetic sequence,直到第一个diff[j]!=diff[i]; ++i

比如输入为:[1, 3, 5, 7, 2, 7, 7, 7, 7]

   diff =  [0, 2, 2, 2,-5, 5, 0,0,0]

i=1时,j=2开始, 到j=3都有diff[j]==diff[i],但是j=4,就不相等,则跳出当前循环

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        vector<int> diff(A.size(), 0);
        for (int i = 1; i < A.size(); ++i) {
            diff[i] = A[i]-A[i-1];
        }
        
        int cnt = 0;
        for (int i = 1; i < diff.size(); ++i) {
            for (int j = i+1; j < diff.size(); ++j) {
                if (diff[i] == diff[j]) {
                    cnt++;
                } else {
                    break;
                }
            }        
        }
        return cnt;
    }
};

时间负责度最坏情况是O(n2), 对应整个输入数组是arithmetic sequence的情况

最好情况是O(n)对应整个输入数组没有arithmetic sequence的情况

 

posted @ 2017-08-27 19:02  糯米团子syj  阅读(147)  评论(0编辑  收藏  举报