【力扣LeetCode】 349_两个数组的交集
- 第 128 篇 -
Date: 2025 - 09 - 23
Author: 郑龙浩(仟墨)
文章目录
- 【力扣LeetCode】 349_两个数组的交集
- 题目描述
- 方法1
- 方法2
【力扣LeetCode】 349_两个数组的交集
题目描述
给定两个数组 nums1 和 nums2 ,返回 它们的 交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
方法1
利用unordered_set容器的自动去重的特性,分两步解决:
- 去重预处理:将两个数组分别转换为哈希集合,自动去除重复元素
- 利用函数查找:遍历其中一个集合,在另一个集合中查找是否存在相同元素
// 350_两个数组的交集
// Author: 郑龙浩 Date: 2025年09月19日
// 用时:18min
#include "bits/stdc++.h"
using namespace std;// 方法1,思路:
// 先将2个数组存入set哈希表
// 然后遍历set2哈希表,每个元素在set2中查找,如果找到,证明为相交元素
class Solution {
public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set <int> set1(nums1.begin(), nums1.end());unordered_set <int> set2(nums2.begin(), nums2.end());vector <int> ans;for (int it : set2) { // 如果元素重合,就插入到数组if (set1.find(it) != set1.end()) ans.push_back(it);}return ans;}};
int main(void) {ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);// vector <int> nums1 = {1, 2, 2, 1}, nums2 = {2, 2};vector <int> nums1 = {4, 9, 5}, nums2 = {9, 4, 9, 8, 4};Solution sol;auto ans = sol.intersection(nums1, nums2);for (auto it = ans.begin(); it != ans.end(); it++) {cout << *it << ' ';}return 0;
}
方法2
采用排序预处理+双指针扫描的策略:
- 排序预处理:对两个数组进行排序,使相同元素相邻
- 双指针扫描:使用两个指针同步遍历数组,寻找公共元素
- 动态去重:使用哈希集合在插入时自动去重
// 350_两个数组的交集
// Author: 郑龙浩 Date: 2025年09月19日
// 用时:18min
#include "bits/stdc++.h"
using namespace std;// 方法2,思路:双指法
// 先对两个数组进行排序
// 使用双指针,不断将两个数组中重复元素插入一个set哈希表中(可以去重)
// 然后返回的时候将哈希表转换为vector数组
class Solution {
public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set <int> ans_nums;int i = 0, j = 0;int len1 = nums1.size(), len2 = nums2.size();sort(nums1.begin(), nums1.end());sort(nums2.begin(), nums2.end());while (i < len1 && j < len2) {if (nums1[i] < nums2[j])i++;else if (nums1[i] > nums2[j])j++;else {ans_nums.insert(nums1[i]); // 元素相同就插入i++; j++;}} return vector <int> (ans_nums.begin(), ans_nums.end());}
};
int main(void) {ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);// vector <int> nums1 = {1, 2, 2, 1}, nums2 = {2, 2};vector <int> nums1 = {4, 9, 5}, nums2 = {9, 4, 9, 8, 4};Solution sol;auto ans = sol.intersection(nums1, nums2);for (auto it = ans.begin(); it != ans.end(); it++) {cout << *it << ' ';}return 0;
}