LC.P2670[找出不同元素数目差数组] 方法一:暴力123456789101112131415161718192021222324class 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)$ 方法二:哈希表+预处理1234567891011121314151617class 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)$