public class Solution { public int NumberOfArithmeticSlices(int[] A) { int curr = 0, sum = 0; for (int i = 2; i < A.Length; i++) if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { curr += 1; sum += curr; } else { curr = 0; } return sum; } }
https://leetcode.com/problems/arithmetic-slices/#/description
补充一个java的实现:
1 class Solution { 2 public int numberOfArithmeticSlices(int[] A) { 3 if (A == null || A.length == 0) { 4 return 0; 5 } 6 int n = A.length; 7 int[] dp = new int[n]; 8 for (int i = 2; i < n; i++) { 9 if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { 10 dp[i] = dp[i - 1] + 1; 11 } 12 } 13 int total = 0; 14 for (int cnt : dp) { 15 total += cnt; 16 } 17 return total; 18 } 19 }
解释:
dp[i] 表示以 A[i] 为结尾的等差递增子区间的个数。
因为递增子区间不一定以最后一个元素为结尾,可以是任意一个元素结尾,因此需要返回 dp 数组累加的结果。