From 703bdfc5dfc9ec7b116e957d8a00dfb3e30d676f Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Tue, 22 Nov 2022 23:47:11 +0800 Subject: [PATCH] add 413 --- README.md | 1 + solutions/413. Arithmetic Slices.md | 32 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 solutions/413. Arithmetic Slices.md diff --git a/README.md b/README.md index 4c54c2b..cc1493f 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 406 |[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/)|[C++](solutions/406.%20Queue%20Reconstruction%20by%20Height.md)|Medium| | | 409 |[Longest Palindrome](https://leetcode.com/problems/longest-palindrome)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/409.%20Longest%20Palindrome.md)|Easy| | | 412 |[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)|[C++](solutions/412.%20Fizz%20Buzz.md)|Easy| | +| 413 |[Arithmetic Slices](https://leetcode.cn/problems/arithmetic-slices/)|[C++](solutions/413.%20Arithmetic%20Slices.md)|Medium| | | 414 |[Third Maximum Number](https://leetcode.com/problems/third-maximum-number)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/414.%20Third%20Maximum%20Number.md)|Easy| | | 415 |[Add Strings](https://leetcode.com/problems/add-strings)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/415.%20Add%20Strings.md)|Easy| | | 416 |[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/416.%20Partition%20Equal%20Subset%20Sum.md)|Medium| | diff --git a/solutions/413. Arithmetic Slices.md b/solutions/413. Arithmetic Slices.md new file mode 100644 index 0000000..1f51bf8 --- /dev/null +++ b/solutions/413. Arithmetic Slices.md @@ -0,0 +1,32 @@ +# [413. Arithmetic Slices](https://leetcode.cn/problems/arithmetic-slices/) + +# 思路 +题目要求一个数组中存在多少个构成等差数列的子数组。注意子数组是数组中的一个**连续**序列。由于要求连续,我们可以先考虑一个长度为 n 的等差数列,有多少个子数组呢?很显然长度为3的有n-2个、长度为4的有n-3个、......长度为n的有1个,故一共有 1 + 2 + ... + (n-2) = (n-1)(n-2)/2 个。 + +所以我们可以从前往后遍历数组nums,找到长度尽可能长的上述等差数列,这样就可以计算出这个等差数列有多少子数组了。 + +由于只用遍历一遍,故复杂度为O(n)。 + +# C++ +```C++ +class Solution { +public: + int numberOfArithmeticSlices(vector& nums) { + if(nums.size() < 3) return 0; + int res = 0; + // d为当前等差数列的差, cnt为当前等差数列的长度 + int d = nums[1] - nums[0], cnt = 2; + for(int i = 2; i < nums.size(); i++){ + if(nums[i] == nums[i-1] + d){ + cnt += 1; + }else{ // 差发生变化, 计算结果 + if(cnt >= 3) res += (cnt - 2) * (cnt - 1) / 2; + d = nums[i] - nums[i-1]; // 更新差和长度 + cnt = 2; + } + } + if(cnt >= 3) res += (cnt - 2) * (cnt - 1) / 2; + return res; + } +}; +``` \ No newline at end of file