mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 413
This commit is contained in:
parent
a7aab80fa0
commit
703bdfc5df
@ -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| |
|
||||
|
32
solutions/413. Arithmetic Slices.md
Normal file
32
solutions/413. Arithmetic Slices.md
Normal file
@ -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<int>& 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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user