leetcode 413. Arithmetic Slices
来源:互联网 发布:java replace '' 编辑:程序博客网 时间:2024/05/24 01:44
1.题目
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
等差数列的定义为:至少三个数字组成,两两相邻的数字之差相同。
等差数列,例如:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
不是等差数列:1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], …, A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
一个下标从0开始的数组A,长度为N。 一个数组切片(P,Q), 满足0<=P
2.分析
两种方法。
方法1: solution里看到的dp
设dp[i]表示以A[i]为结尾的切片数量,那么dp[i+1]=dp[i]+1
例如 1 1 2 3 4
以3为结尾的切片有 1 2 3
以4位结尾的切片有 1 2 3 4 , 2 3 4 多出来的就是2 3 4,所以dp[i+1]=dp[i]+1
按照这个递推公式依次求解,求和。
方法2:找出每一段等差数列,根据长度求可能的切片个数。
例如: 1 1 2 3 4
1 2 3 4是等差数列,长度为切片的可能有1 2 3、2 3 4,1 2 3 4
长度为x的等差数列切片的数量为 x-2+x-3+x-4…+1=(x-2)(x-1)/2
最后求总和即可。
3.代码
方法1:
class Solution {public: int numberOfArithmeticSlices(vector<int>& A) { int count = 0; int total = 0; int j = 2; while (j < A.size()) { if (A[j-1] - A[j - 2] == A[j] - A[j-1]) count += 1; else count = 0; total += count; ++j; } return total; }};
方法2
int numberOfArithmeticSlices(vector<int>& A) { if (A.size() < 3) return 0; int* diff = new int[A.size() - 1]; for (int i = 1; i < A.size(); i++) diff[i - 1] = A[i] - A[i - 1];//相邻元素的差 int total = 0; int i = 0; while (i < A.size() - 1){ int j = i; while (j < A.size() - 2 && diff[j] == diff[j + 1]) ++j; if (j > i) total += (j - i)* (j - i + 1) / 2; i = j + 1; } return total;}
- [LeetCode]413.Arithmetic Slices
- Leetcode 413. Arithmetic Slices
- Leetcode-413. Arithmetic Slices
- 【LeetCode】413. Arithmetic Slices
- Leetcode-413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- Leetcode 413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- [LeetCode]413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- 【LeetCode】 413. Arithmetic Slices
- [LeetCode]413. Arithmetic Slices
- [leetcode]413. Arithmetic Slices
- [Leetcode] 413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- [leetcode]--413. Arithmetic Slices
- 【LeetCode】413. Arithmetic Slices
- sqlserver字段类型详解
- 关于VS与opencv安装配置过程中遇到的问题
- JQuery
- L1-005. 考试座位号
- 上拉电阻解决1036串口接收乱码问题
- leetcode 413. Arithmetic Slices
- Python3.X中的函数
- PHP深入学习
- 操作系统-文件系统
- 多线程下载以及断点续传
- servlet异常如何处理
- BZOJ 1221: [HNOI2001] 软件开发 费用流 多路增广
- Springmvc搭建简单测试demo
- PAT (Advanced Level) Practise 1010