leetcode_413. Arithmetic Slices 数组中连续的等差数列个数
来源:互联网 发布:微课录屏制作软件 编辑:程序博客网 时间:2024/06/13 06:27
题目:
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.
For example, these are arithmetic sequence:
1, 3, 5, 7, 97, 7, 7, 73, -1, -5, -9
The following sequence is not arithmetic.
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.
Example:
A = [1, 2, 3, 4]return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
题意:
给定数组A,求A中长度至少为3,且位置连续的等差数列的个数
代码:
class Solution(object):
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
n = len(A)
if n < 3 :
return 0
else :
res = 0 #记录等差数列个数
add = 0 #记录在原来等差数列基础上增加一个元素形成新的等差数列后,原来的等差数列个数需要增加的数目
for i in range(2,n) :
if A[i]-A[i-1] == A[i-1]-A[i-2] :
add += 1
res += add #在原来的基础上,增加元素后等差数列总数需要增加的数目
else :
add = 0
return res
笔记:
参考了两个大神的思路:
http://www.bubuko.com/infodetail-1800825.html
http://blog.csdn.net/camellhf/article/details/52824234
- leetcode_413. Arithmetic Slices 数组中连续的等差数列个数
- [LeetCode] Arithmetic Slices 等差数列的个数
- LeetCode 413 Arithmetic Slices (找等差数列)
- 413. Arithmetic Slices (找等差数列)
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- Arithmetic Slices
- J Arithmetic Sequence (华农第四届) 求数组中最长等差数列
- 查找一个数组中不连续0出现的个数
- 找出数组中长度最长的等差数列
- 413. Arithmetic Slices
- [LeetCode]413.Arithmetic Slices
- LeetCode: Arithmetic Slices
- JSP——1
- codeforces - 508B - Anton and currency you all know(贪心)
- NodeJS基础API搭建服务器详细过程记录
- 【总结】软件工程视频(一)
- Android 加载动画(关于SpinKit的使用)
- leetcode_413. Arithmetic Slices 数组中连续的等差数列个数
- 第1章 ECS
- linux shell编程之——if语句
- 构建 Android APP 一定要绕过的 30 个坑
- wikioi 2315 longge的问题 2012年省队选拔赛山东(欧拉函数应用)
- python读取excel数据
- HTML5十五大新特性
- vue里一些问题
- 杂乱数据点滴笔记