1. 程式人生 > >LeetCode 413.Arithmetic Slices 解題報告

LeetCode 413.Arithmetic Slices 解題報告

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:
description1
The following sequence is not arithmetic.
description2

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

限制條件

沒有明確給出.

解題思路

我的思路:

這道題的題目不是一般的長,其實就是一個意思:給你一串數字,返回這串數字中能夠構成等差數列的子串的數目。
我的想法是通過掃描一遍陣列就能得到結果,所以得先知道如果掃描發現下一個數字能夠加入到等差數列中,那麼總的數目會有怎樣的變化。
因此,我列出了下表:

陣列 等差數列的數目 與上一陣列的等差數列數目比較
1 2 3 1 1 - 0 = 1
1 2 3 4 3 3 - 1 = 2
1 2 3 4 5 6 6 - 3 = 3
1 2 3 4 5 6 10 10 - 6 = 4
1 2 3 4 5 6 7 15 15 - 10 = 5

觀察就能發現兩個等差數列數目之差(表格第三列)就是[1,2, 3, 4, 5……]這個序列,因此每次增加一個等差數列的元素,總的等差數列的數目就會增加[1,2, 3, 4, 5……]中對應的數值。

按照這一點,在程式碼實現時就設定一個變數addend,表示增加的數目,它對應著[1,2, 3, 4, 5……]這個序列,如果下一個陣列元素能夠加入到等差數列中,addend就自增1,然後總的數目就增加addend。如果下一個陣列元素不能加入到等差數列中,addend就重置為0。這樣通過一個迴圈就能獲得結果。

做完看了看其他人的程式碼,目前發現的最好的解法就是跟我一樣的,似乎還沒有更好的,其他稍複雜的解法就不貼出來了。

程式碼

我的程式碼

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int count = 0;
        int addend = 0;

        for (int i = 2; i < A.size(); i++)
            if (A[i - 1] - A[i] == A[i - 2] - A[i - 1])
                count += ++addend;
            else 
                addend = 0;

        return count;
    }
};

總結

這道新題雖然長,但是看懂了之後會發現其實不難,就是找找規律而已,所以在紙上寫寫就能很快做出來了。
今天填了好幾個坑,會寫兩篇解題報告,繼續寫下一篇!加油加油!