Skip to content

Commit 63da990

Browse files
refactor 413
1 parent 38753de commit 63da990

File tree

1 file changed

+28
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-22
lines changed

src/main/java/com/fishercoder/solutions/_413.java

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
package com.fishercoder.solutions;
22

3-
/**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.
3+
/**
4+
* 413. Arithmetic Slices
5+
*
6+
* 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.
47
58
For example, these are arithmetic sequence:
69
710
1, 3, 5, 7, 9
811
7, 7, 7, 7
912
3, -1, -5, -9
13+
1014
The following sequence is not arithmetic.
1115
1216
1, 1, 2, 5, 7
@@ -18,40 +22,42 @@ A slice (P, Q) of array A is called arithmetic if the sequence:
1822
1923
The function should return the number of arithmetic slices in the array A.
2024
21-
2225
Example:
2326
2427
A = [1, 2, 3, 4]
2528
26-
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.*/
29+
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
30+
*/
2731
public class _413 {
2832

29-
//copied this solution: https://discuss.leetcode.com/topic/62884/2ms-java-o-n-time-o-1-space-solution
30-
public int numberOfArithmeticSlices(int[] A) {
31-
int sum = 0;
32-
int len = 2;
33-
for (int i = 2; i < A.length; i++) {
34-
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
35-
len++;
36-
} else {
37-
if (len > 2) {
38-
sum += calculateSlices(len);
33+
public static class Solution1 {
34+
//credit: https://discuss.leetcode.com/topic/62884/2ms-java-o-n-time-o-1-space-solution
35+
public int numberOfArithmeticSlices(int[] A) {
36+
int sum = 0;
37+
int len = 2;
38+
for (int i = 2; i < A.length; i++) {
39+
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
40+
len++;
41+
} else {
42+
if (len > 2) {
43+
sum += calculateSlices(len);
44+
}
45+
len = 2;//reset it to 2
3946
}
40-
len = 2;//reset it to 2
4147
}
48+
if (len > 2) {
49+
sum += calculateSlices(len);
50+
}
51+
return sum;
4252
}
43-
if (len > 2) {
44-
sum += calculateSlices(len);
45-
}
46-
return sum;
47-
}
4853

49-
int calculateSlices(int len) {
50-
return (len - 1) * (len - 2) / 2;
54+
int calculateSlices(int len) {
55+
return (len - 1) * (len - 2) / 2;
56+
}
5157
}
5258

5359
class Solution2 {
54-
//a more clear solution: https://discuss.leetcode.com/topic/63302/simple-java-solution-9-lines-2ms
60+
//credit: https://discuss.leetcode.com/topic/63302/simple-java-solution-9-lines-2ms
5561
public int numberOfArithmeticSlices(int[] A) {
5662
int sum = 0;
5763
int curr = 0;

0 commit comments

Comments
 (0)