[LeetCode]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.

這一題咋看之下,還以爲使用動態規劃,輔助數組空間換時間來做,後來發現我想多了。

只要發現這種數列的成型特徵就可以很好做了這一題。思路:我們可以發現所有的數列,必定是從P開始,到Q結束,這種之間是沒有中斷的。因此,我們遍歷一遍數組,計算以每一個數字開頭的數列的數量即可。

具體來說,對於給定的開頭數字,A[P],先計算A[P],A[P+1],A[P+2],是不是數列,如果是,將總數++。繼續往後計算,只用計算A[p+3]-A[p+2]的值和前面數列的公差是否相等,就可以判斷是不是一個新的數列,將總數++即可。

需要注意的是,在遍歷以給定數字A[P]開頭的數列時,一旦出現不是數列,可以立刻跳出這個循環,開始遍歷以A[P+1]開頭的數列。因爲就算是A[P]這一行後面還有數列,但是這個數列都不是以A[P]開頭的了,後面的遍歷中會算到這個數列的。

public class Solution {

	public int numberOfArithmeticSlices(int[] A) {
		if (A.length < 3) {
			return 0;
		}
		int nTotal = 0;
		for (int i = 0; i < A.length - 2; i++) {
			int nCurrentIndex = i;
			int nCurrentDiff = Integer.MAX_VALUE;
			// find first seq
			if (isSeq(A[nCurrentIndex], A[nCurrentIndex + 1], A[nCurrentIndex + 2])) {
				nCurrentDiff = A[nCurrentIndex + 1] - A[nCurrentIndex];
				nTotal++;
				nCurrentIndex += 3;
				// find follow seq
				while (nCurrentIndex < A.length) {
					if (A[nCurrentIndex] - A[nCurrentIndex - 1] == nCurrentDiff) {
						nTotal++;
						nCurrentIndex++;
					} else {
						break;
					}
				}
			}
		}
		return nTotal;

	}

	private boolean isSeq(int a, int b, int c) {
		return b - a == c - b ? true : false;
	}
}

以上代碼的複雜度爲O(n^2),由於大量的內層循環都沒有遍歷所有剩下的數,具體來說運行時間應該遠小於(n+1)n/2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章