-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
70 lines (61 loc) · 1.42 KB
/
res.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-04-13 11:02:22
*
* 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.
*
* @param {number[]} A
* @return {number}
*/
let numberOfArithmeticSlices = function(A) {
let len = A.length;
if (len < 3) {
return 0;
}
let res = 0,
interval = [];
// 构建元素差数组
for (let i = 1; i < len; i++) {
interval.push(A[i] - A[i - 1]);
}
let count = 2,
difPre = interval[0];
len--;
for (let i = 1; i < len; i++) {
let difNow = interval[i];
if (difNow === difPre) {
count++;
} else {
res += Sum(count); // 计算当前积攒元素个数下的 arithmetic 个数
difPre = difNow;
count = 2;
}
}
if (count > 2) {
res += Sum(count);
}
return res;
};
let Sum = function(n) {
// console.log(n);
return (n - 2) * (n - 1) / 2;
};
/**
* Another solution
*/
// let solution = function(A) {
// let curr = 0,
// sum = 0;
// for (let i = 2; i < A.length; i++)
// if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
// curr += 1;
// sum += curr;
// } else {
// curr = 0;
// }
// return sum;
// }