自己的版本:排序 + 双指针 + 哈希表 vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
set<int> hash;
vector<int> ret;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int p1 = 0, p2 = 0;
while(p1 < nums1.size() && p2 < nums2.size())
{
if(nums1[p1] == nums2[p2])
{
hash.insert(nums1[p1]);
p1++;
p2++;
}
else if(nums1[p1] < nums2[p2])
{
p1++;
}
else
{
p2++;
}
}
for(const auto& x : hash)
{
ret.push_back(x);
}
return ret;
}
优化版本:直接用哈希表
- 哈希表用原生数组模拟即可(
true
为在,false
为不在)
- 为避免重复,在找到相同元素之后,可将哈希表中的值删除
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
bool hash[1001] = { 0 };
vector<int> ret;
for(const auto& x : nums1)
{
hash[x] = true;
}
for(const auto& x : nums2)
{
ret.push_back(x);
hash[x] = false;
}
return ret;
}