LC.P446[等差数列划分II-子序列]

方法一:动态规划+哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int ans = 0, n = nums.length;
Map<Long, Integer>[] f = new Map[n];
for (int i = 0; i < n; ++i) {
f[i] = new HashMap<>();
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
long d = (long) nums[i] - nums[j];
int cnt = f[j].getOrDefault(d, 0);
ans += cnt;
f[i].put(d, f[i].getOrDefault(d, 0) + cnt + 1);
}
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n^2)$