[LeetCode] 413. Arithmetic Slices

A sequence of numbers 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 sequences:

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 the 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.

等差数列划分。

如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。

例如,以下数列为等差数列:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
以下数列不是等差数列。

1, 1, 2, 5, 7

数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。

如果满足以下条件,则称子数组(P, Q)为等差数组:

元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。

函数要返回数组 A 中所有为等差数组的子数组个数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/arithmetic-slices
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是动态规划。我们创建一个与 input 数组等长的dp数组,dp数组的定义是以 nums[i] 为结尾的最长的等差数列的长度是多少。这道题的思路类似53题。

时间O(n)

空间O(1) - 可以不需要额外空间

Java实现

 1 class Solution {
 2     public int numberOfArithmeticSlices(int[] A) {
 3         int[] dp = new int[A.length];
 4         int sum = 0;
 5         for (int i = 2; i < dp.length; i++) {
 6             if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
 7                 dp[i] = dp[i - 1] + 1;
 8                 sum += dp[i];
 9             }
10         }
11         return sum;
12     }
13 }

不需要额外空间的实现

 1 class Solution {
 2     public int numberOfArithmeticSlices(int[] A) {
 3         int sum = 0;
 4         int dp = 0;
 5         for (int i = 2; i < A.length; i++) {
 6             if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
 7                 dp = dp + 1;
 8                 sum += dp;
 9             } else {
10                 dp = 0;
11             }
12         }
13         return sum;
14     }
15 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14414305.html