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, 9
7, 7, 7, 7
3, -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.

 
  数组的切片(slice,不知道是不是这么翻译?)定义如下:对于一个含N(N>=3)个元素的数组A,设它的某个子数组B,数组B含L(L>=3)个元素,若数组B的元素构成一个等差数列,则称数组B为数组A的一个切片。
  现给定一个含N个元素的数组A,判定其切片个数。
分析:
  本题要求一个数组所含有的构成等差数列的子数组的个数。我们知道,长度为L的等差数列S,含(L-M+1)个长度为M的子数列S m,因此,数列S构成的数列含有的切片数为(L-3+1)+(L-4+1)+…+(L-L+1)。而一个数组A,可能含有多个这样的子数组,即前i个元素含有长为L i,差为d i的等差子数组,第i个元素到第j个元素含有长为L j,差为d j的等差子数组,…,第k个元素到第n个元素含有长为L n,差为d n的等差子数组,求数组A的切片即求这些等差子数组的切片数。
 
代码如下:
int numberOfArithmeticSlices(vector<int>& A)
{
	int len = A.size();
	int cnt = 0;
	for (int i = 0; i < len - 1; i++)
	{
		int delta = A[i + 1] - A[i];
		int cur = 2;
		for (int j = i + 2; j < len; j++)
		{
			if (A[j] - A[j-1] == delta)
				cur++;
			else
				break;
		}
		if (cur >= 3)
		{
			i += cur - 1;
			int tmp = 3;
			while (cur >= tmp)
			{
				cnt += cur - tmp + 1;
				tmp += 1;
			}
		}
	}
	return cnt;
}

  

posted on 2018-03-26 19:37 bigpotato 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/big-potato/p/8653064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值