题目:
给你一个下标从 0 开始的数组 nums
,数组长度为 n
。
nums
的 不同元素数目差 数组可以用一个长度为 n
的数组 diff
表示,其中 diff[i]
等于前缀 nums[0, ..., i]
中不同元素的数目 减去 后缀 nums[i + 1, ..., n - 1]
中不同元素的数目。
返回 nums
的 不同元素数目差 数组。
注意 nums[i, ..., j]
表示 nums
的一个从下标 i
开始到下标 j
结束的子数组(包含下标 i
和 j
对应元素)。特别需要说明的是,如果 i > j
,则 nums[i, ..., j]
表示一个空子数组。
思路:
使用两个哈希表,去储存index之前和之后的元素,然后前一个哈希表的长度减去后一个哈希表的长度即可。
代码:
class Solution {
public:
vector<int> distinctDifferenceArray(vector<int>& nums) {
vector<int>rtu;
int i;
int len=nums.size();
for(i=0;i<len;i++){
map<int,int>hash1;
map<int,int>hash2;
for(int j=0;j<=i;j++){
hash1[nums[j]]++;
}
for(int a=i+1;a<len;a++){
hash2[nums[a]]++;
}
rtu.push_back(hash1.size()-hash2.size());
}
return rtu;
}
};
或者使用哈希表加前后缀处理
class Solution {
public:
vector<int> distinctDifferenceArray(vector<int>& nums) {
int n = nums.size();
unordered_set<int> st;
vector<int> sufCnt(n + 1, 0);
for (int i = n - 1; i > 0; i--) {
st.insert(nums[i]);
sufCnt[i] = st.size();
}
vector<int> res;
st.clear();
for (int i = 0; i < n; i++) {
st.insert(nums[i]);
res.push_back(int(st.size()) - sufCnt[i + 1]);
}
return res;
}
};