-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arithmetic Slices II - Subsequence.java
69 lines (55 loc) · 2.14 KB
/
Arithmetic Slices II - Subsequence.java
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
/*
A sequence of numbers 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 sequences:
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 subsequence slice of that array is any sequence
of integers (P0, P1, ..., Pk) such that 0 ≤ P0 < P1 < ... < Pk < N.
A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic if the sequence A[P0], A[P1], ...,
A[Pk-1], A[Pk] is arithmetic. In particular, this means that k ≥ 2.
The function should return the number of arithmetic subsequence slices in the array A.
The input contains N integers. Every integer is in the range of -231 and 2^{31}-1 and 0 ≤ N ≤ 1000. The output
is guaranteed to be less than 231-1.
Link: https://leetcode.com/problems/arithmetic-slices-ii-subsequence/
Example:
Input: [2, 4, 6, 8, 10]
Output: 7
Explanation:
All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
Solution: None
Source: https://discuss.leetcode.com/topic/67012/java-15-lines-solution/2
*/
public class Solution {
public int numberOfArithmeticSlices(int[] A) {
int re = 0;
HashMap<Integer, Integer>[] maps = new HashMap[A.length];
for (int i=0; i < A.length; i++) {
maps[i] = new HashMap<>();
int num = A[i];
for (int j = 0; j < i; j++) {
if ((long)num - A[j] > Integer.MAX_VALUE) {
continue;
}
if ((long)num - A[j] < Integer.MIN_VALUE) {
continue;
}
int diff = num - A[j];
int count = maps[j].getOrDefault(diff, 0);
maps[i].put(diff, maps[i].getOrDefault(diff, 0) + count + 1);
re += count;
}
}
return re;
}
}