bigpotato

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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的子数列Sm,因此,数列S构成的数列含有的切片数为(L-3+1)+(L-4+1)+…+(L-L+1)。而一个数组A,可能含有多个这样的子数组,即前i个元素含有长为Li,差为di的等差子数组,第i个元素到第j个元素含有长为Lj,差为dj的等差子数组,…,第k个元素到第n个元素含有长为Ln,差为dn的等差子数组,求数组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  阅读(132)  评论(0)    收藏  举报