413. Arithmetic Slices

网友投稿 745 2022-11-11

413. Arithmetic Slices

413. Arithmetic Slices

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.

思路: 直接从头开始找等差数列,假设有一段等差数列的长度为n (n >= 3),则其包含的等差数列个数是(n-2)*(n-2+1)/2,所以直接扫一下即可,时间复杂度O(n)。

class Solution public int numberOfArithmeticSlices(int[] A) { int sz = A.length, cur = 0, sum = 0; for (int i = 1; i < sz - 1; i ++) { if (A[i] - A[i - 1] == A[i + 1] - A[i]) { cur ++; sum += cur; } else { cur = 0; } } return sum; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:396. Rotate Function
下一篇:基于Maven pom文件中属性变量总结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~