LeetCode刷题实战413:等差数列划分
共 1919字,需浏览 4分钟
·
2021-10-21 07:19
An integer array 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, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
示例
示例 1:
输入:nums = [1,2,3,4]
输出:3
解释:nums 中有三个子等差数组:[1, 2, 3]、[2, 3, 4] 和 [1,2,3,4] 自身。
示例 2:
输入:nums = [1]
输出:0
解题
长度为n的等差数列中,自身以及它的子集,个数一共有(n-1)*(n-2)/2。
dx为等差数列中两个相邻元素的差的绝对值。数组中两个dx不想等的等差数列最多可能有一个重复使用的点。例如1,2,3,6,9。3即使那个重复的值,分别是1,2,3的尾,以及3,6,9的头。
class Solution {
public:
#define numberOfNsize(x) (((x-1)*(x-2))>>1)
int numberOfArithmeticSlices(vector<int>& A) {
//存储A中出现过的连续的等差数列的最长长度
int size = A.size();
int pos = 0;
int res = 0;
while (pos < size-2) {
//试图从pos往后查询一个等差数列
int dx = A[pos + 1] - A[pos];
int next = pos + 1;
while ((next-1] == dx)) {
next++;
}
int length = next - pos;
pos = next-1;
if (length >= 3) res += numberOfNsize(length);
}
return res;
}
};