共计 1580 个字符,预计需要花费 4 分钟才能阅读完成。
题目要求
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.
将包含大于等于三个元素且任意相邻两个元素之间的差相等的数组成为等差数列。现在输入一个随机数组,问该数组中一共可以找出多少组等差数列。
思路一:动态规划
假设已经知道以第 i - 1 个数字为结尾有 k 个等差数列,且第 i 个元素与 i - 1 号元素和 i - 2 号元素构成了等差数列,则第 i 个数字为结尾的等差数列个数为 k +1。因此我们可以自底向上动态规划,记录每一位作为结尾的等差数列的个数,并最终得出整个数列中等差数列的个数。代码如下:
public int numberOfArithmeticSlices(int[] A) {int[] dp = new int[A.length];
int count = 0;
for(int i = 2 ; i<A.length ; i++) {if(A[i] - A[i-1] == A[i-1] - A[i-2]) {dp[i] = dp[i-1] + 1;
count += dp[i];
}
}
return count;
}
思路二:算数方法
首先看一个简单的等差数列 1 2 3
,可知该数列中一共有 1 个等差数列
再看 1 2 3 4
,可知该数列中一共有 3 个等差数列,其中以 3 为结尾的 1 个,以 4 为结尾的 2 个
再看1 2 3 4 5
, 可知该数列中一共有 6 个等差数列,其中以 3 为结尾的 1 个,4 为结尾的 2 个,5 为结尾的 3 个。
综上,我们可以得出,如果是一个最大长度为 n 的等差数列,则该等差数列中一共包含的等差数列个数为(n-2+1)*(n-2)/2
,即(n-1)*(n-2)/2
。
因此,我们只需要找到以当前起点为开始的最长的等差数列,计算该等差数列的长度并根据其长度得出其共包含多少个子等差数列。
代码如下:
public int numberOfArithmeticSlices2(int[] A) {if(A.length <3) return 0;
int diff = A[1]-A[0];
int left = 0;
int right = 2;
int count = 0;
while(right < A.length) {if(A[right] - A[right-1] != diff) {count += (right-left-1) * (right-left-2) / 2;
diff = A[right] - A[right-1];
left = right-1;
}
right++;
}
count += (right-left-1) * (right-left-2) / 2;
return count;
}
正文完