LC.P2670[找出不同元素数目差数组]

方法一:暴力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int[] distinctDifferenceArray(int[] nums) {
Set<Integer> set = new HashSet<>();
int n = nums.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i; ++j) {
if (!set.contains(nums[j])) {
set.add(nums[j]);
ans[i]++;
}
}
set.clear();
for (int j = n - 1; j > i; --j) {
if (!set.contains(nums[j])) {
set.add(nums[j]);
ans[i]--;
}
}
set.clear();
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$

方法二:哈希表+预处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] distinctDifferenceArray(int[] nums) {
Set<Integer> set = new HashSet<>();
int n = nums.length;
int[] ans = new int[n], suffix = new int[n + 1];
for (int i = n - 1; i >= 0; --i) {
set.add(nums[i]);
suffix[i] = set.size();
}
set.clear();
for (int i = 0; i < n; ++i) {
set.add(nums[i]);
ans[i] = set.size() - suffix[i + 1];
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$