413. Arithmetic Slices
https://leetcode.com/problems/arithmetic-slices/
Python
- 4個元素的等差數列,可能組合為:
- 5個元素的等差數列,可能組合為:
- n個元素的等差數列,可能的組合為:
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
if len(nums) < 3:
return 0
arith_length = 0
counter = 0
for i in range(len(nums)-2):
if nums[i+2] - nums[i+1] == nums[i+1] - nums[i]:
arith_length += 1
counter += arith_length
else:
arith_length = 0
return counter