Skip to main content

413 Arithmetic Slices

Leetcode

An integer array 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, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums.

A subarray is a contiguous subsequence of the array.

Example 1:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:

Input: nums = [1]
Output: 0

如果 nums[i]-nums[i-1]=nums[i-1]-nums[i-2] ,则这是一个等差数列。如果 nums[i] 已经与前面两个数是等差数列了,而 nums[i+1] 也与前面两个数是等差数列,则新增了 2 个等差数列,如果下一个元素还是,则增加 3 个。用一个数组记录当前元素新增了几个等差数列,最后求和。

public int numberOfArithmeticSlices(int[] nums) {
int[] arr=new int[nums.length+1];
for(int i=2;i<nums.length;++i){
if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){
arr[i]=arr[i-1]+1;
}
}
int total=0;
for(int i:arr){
total+=i;
}
return total;
}