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.
思路
这道dp题好不容易会做,结果这个bug改到我快吐了,说明基本功不扎实…
题外话,题目中的difference原来还有“差”的意思(到处都是知识盲区)
整体思路就是用dp数组记录当前等差的连续元素数,当差值不相等时,需要结算一下前一个元素区间。在循环结束后,不要忘记结算最后一个元素区间~
代码
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& nums) {
int len = nums.size();
if(len < 3) return 0;
int dp[5005] = {1, 2};
int sum = 0, temp = nums[1] - nums[0];
for(int i = 2; i < len; i++)
{
if(nums[i] - nums[i-1] == temp)
dp[i] = dp[i-1] + 1;
else
{
if(dp[i-1] >= 3)
sum += 0.5*(dp[i-1]*dp[i-1]-3*dp[i-1]+2);
dp[i] = 2;
temp = nums[i] - nums[i-1];
}
}
if(dp[len-1] >= 3)
sum += 0.5*(dp[len-1]*dp[len-1]-3*dp[len-1]+2);
return sum;
}
};