LeetCode學習篇八—— 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.

難度:medium 通過率:53.3%

這道題的題目寫了很多東西,一開始看了是不知道要求什麼的 ,然後再看了一下例子,原來粗暴地理解就是要求所給序列裏存在多少個長度不小於3的等差數列 。
想着從頭到尾遍歷一次,但是怎麼判斷符合條件子序列的數目呢?
於是列了幾個例子總結出了規律:

序列 符合子序列數目 規律
[1,2,3] 1 1
[1,2,3,4] 3 1+2
[1,2,3,4,5] 6 1+2+3
[1,2,3,4,5,6] 10 1+2+3+4

由以上表格可知,如果成連續子序列每多一個元素即在原來的數目上加一個遞增的數,從0開始遞增,所以,可以直接從頭開始遍歷序列,用變量temp記錄遞增數,count記錄總數目,當下一個數和前面的序列不成等差數列時,temp再次等於0,由此遍歷下去。代碼如下,複雜度O(n)

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) { 
        int size = A.size();
        int count = 0;
        int temp = 0; 
        if(size < 3) {
            return 0;
        }
        int diff = A[1]-A[0]; 
        for(int i = 2; i < size; i++) {
            if(A[i]-A[i-1] == diff) {
                temp++;
                count += temp;
            }
            else {
                diff = A[i]-A[i-1];
                temp = 0;
            }
        }   
        return count;
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章