Arithmetic Slices LT413
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.
Idea 1. How to extend the solution from A[i...j] to A[i...j+1]? dynamic programming的应用解法,试着想如果A[i..j]是arithmetic sequence,dp[j]是以A[j]结尾的arithmetic sequence的个数,那么
1 class Solution { 2 public int numberOfArithmeticSlices(int[] A) { 3 int count = 0; 4 int curr = 0; 5 for(int i = 2; i < A.length; ++i) { 6 if(A[i-1] - A[i-2] == A[i] - A[i-1]) { 7 ++curr; 8 count += curr; 9 } 10 else { 11 curr = 0; 12 } 13 } 14 return count; 15 } 16 }
python:
1 class Solution: 2 def numberOfArithmeticSlices(self, A: List[int]) -> int: 3 curr: int = 0 4 count: int = 0 5 6 for i in range(2, len(A)): 7 if A[i-1] - A[i-2] == A[i] - A[i-1]: 8 curr += 1 9 count += curr 10 else: 11 curr = 0 12 13 return count
Idea 2. Instead of updating the accumulated sum for each consecutive sequence, only updating the sum once the longest sequence so far is found. 根据公式 curr * (curr+1)/2来计算现在这一段的arithmetic sequence的个数.
总个数 1 + 2 + 3 = (1+3)*3/2 = 6
1 class Solution { 2 public int numberOfArithmeticSlices(int[] A) { 3 int count = 0; 4 int curr = 0; 5 for(int i = 2; i < A.length; ++i) { 6 if(A[i-1] - A[i-2] == A[i] - A[i-1]) { 7 ++curr; 8 } 9 else { 10 count += curr * (curr + 1)/2; 11 curr = 0; 12 } 13 } 14 15 count += curr * (curr + 1)/2; 16 return count; 17 } 18 }
python:
1 class Solution: 2 def numberOfArithmeticSlices(self, A: List[int]) -> int: 3 curr: int = 0 4 count: int = 0 5 6 for i in range(2, len(A)): 7 if A[i-1] - A[i-2] == A[i] - A[i-1]: 8 curr += 1 9 else: 10 count += curr * (curr + 1)/2 11 curr = 0 12 13 count += curr * (curr + 1)/2 14 return int(count)