Leetcode-413 Arithmetic Slices(等差数列划分)

本文深入探讨了如何通过算法解决等差数列中子序列的计数问题,提供了一种有效的方法来计算连续等差片段的数量。通过对代码的逐行解析,揭示了算法背后的逻辑和实现细节。
 1 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 2 class Solution
 3 {
 4     public:
 5         int f(int len)
 6         {
 7             int sum = 0;
 8             len -= 2;
 9             _for(i,1,len+1)
10             sum += i;
11             return sum;
12         }
13         int numberOfArithmeticSlices(vector<int>& A)
14         {
15             int cur = 0;
16             if(A.size()<2)
17                 return 0;
18 
19             int rnt = 0;
20             _for(i,0,A.size())
21             {
22                 if(!cur&&A[i]-A[i+1]==A[i+1]-A[i+2])
23                 {
24                     cur = 3;
25                     i += 2;
26                 }
27                 else if(cur&&A[i]-A[i-1]==A[i-1]-A[i-2])
28                     cur ++;
29                 else
30                 {
31                     rnt += f(cur);
32                     cur = 0;
33                     if(!cur&&A[i]-A[i+1]==A[i+1]-A[i+2])
34                     {
35                         cur = 3;
36                         i += 2;
37                     }
38                 }
39             }
40             rnt += f(cur);
41             return rnt;
42         }
43 };

 

转载于:https://www.cnblogs.com/Asurudo/p/10351668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值