日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

LeetCode - 413. Arithmetic Slices - 含中文题意解释 - O(n) - ( C++ ) - 解题报告

發布時間:2025/4/14 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode - 413. Arithmetic Slices - 含中文题意解释 - O(n) - ( C++ ) - 解题报告 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.題目大意

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.

剛開始看這道題的時候我還挺糾結的,然后發現其實是我對題意的理解有問題,或者說題目本身sample給的也不好。

(1)首先,題目輸入的數列是0索引的數組,注意,這個輸入的數組的各個數字不一定是等差數列,比如說可能輸入的是{1,2,5,6}。

(2)所求的P+1<Q,也就是說所求出的等比數列中至少包含3個元素,比如{1,2,3,4}中{1,2}就不算是arithmetic。

(3)所求的arithmetic在原數組中要求是位置連續的,比如原數組若給定的是{1,2,4,3},這里的{1,2,3}在原數組中并不連續,因此會返回0。而{1,3,5,6}中{1,3,5}位置則是連續的。

再舉幾個例子:

輸入:{1,2} 返回0 。因為沒有3個以上的元素。

輸入:{1,3,5,6,7} 返回2。因為有{1,3,5}和{5,6,7}。而{1,3,5,7}則不算,因為它們在原數組里不連續。

輸入:{1,3,5} 返回1。

?

2.思路

顯而易見:連續的等差數列有n個元素的時候,則會有(1+2+...+n)個等差子數列。

{1,2,3} ->?{1,2,3} ->1

{1,2,3,4} ->?{1,2,3,4} +?{1,2,3} +?{2,3,4}?-> 1+2 ->3

{1,2,3,4,5} ->?{1,2,3,4,5} +?{1,2,3,4} +?{2,3,4,5} +?{1,2,3} +?{2,3,4} + {3,4,5} -> 1+2+3 ->6

{1,2,....,n} -> ...... -> 1+2+...+n ?

?

3.代碼

public:int numberOfArithmeticSlices(vector<int>& A) {int sum=0,count=1;if(A.size()<3) return 0;for(int i=1;i<A.size()-1;i++){if(A[i]-A[i-1]==A[i+1]-A[i]) sum+=(count++);elsecount=1;}return sum;} };

  

轉載于:https://www.cnblogs.com/rgvb178/p/5967894.html

總結

以上是生活随笔為你收集整理的LeetCode - 413. Arithmetic Slices - 含中文题意解释 - O(n) - ( C++ ) - 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。