求两个数组的交集

解题思路:

审题:求交集意味着要从两个无序数组中拿其中的相同的元素,集合中一个数可能出现多次,在返回的数组中,不需要相同的元素。也就是查找两个数组,找数组相同的值,并删除其中重复的元素。

思路:使用一个集合,将其中一个数组的元素存放到集合中,遍历另一个数组,利用集合 Unordered_set 的库函数 count 搜索当前遍历的数组元素,若这个数组元素在集合中存在,则把他插入到新的集合中。因为集合中的元素具有唯一性,所以重复的元素并不会被重复插入到集合。遍历结束,即可得到存放交集的集合,再将新集合的元素用数组保存,返回该数组即可。

1.定义集合nums1Set,保存数组nums1的数组元素

/将nums1中的元素添加到集合
unordered_set<int> nums1Set(nums1.begin(), nums1.end());

2.建立新集合,保存交集。

//定义一个集合用于存放唯一交集
unordered_set<int> uniqueIntersection;

3.遍历另一个数组nums2,将相同的元素插入到新集合uniqueIntersection中

 //遍历nums2,如果元素在nums1Set中存在,则加入交集
for (auto it2 : nums2) 
{
    if (nums1Set.count(it2))     
    {
        uniqueIntersection.insert(it2);
    }
}

4.将集合转为数组

//将集合转为向量
vector<int> newNums(uniqueIntersection.begin(), uniqueIntersection.end());

完整程序代码:

// 两个数组的交集.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<vector>
#include <unordered_set>
using namespace std;

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
    {
        //定义一个集合用于存放唯一交集
        unordered_set<int> uniqueIntersection;
        //将nums1中的元素添加到集合
        unordered_set<int> nums1Set(nums1.begin(), nums1.end());
        //遍历nums2,如果元素在nums1Set中存在,则加入交集
        for (auto it2 : nums2) {
            if (nums1Set.count(it2)) {
                uniqueIntersection.insert(it2);
            }
        }
        //将集合转为向量
        vector<int> newNums(uniqueIntersection.begin(), uniqueIntersection.end());
        return newNums;
    }
};
int main()
{
    Solution solution;

    // 测试1
    vector<int> nums1 = { 1, 2, 2, 1 };
    vector<int> nums2 = { 2, 2 };
    vector<int> result1 = solution.intersection(nums1, nums2);
    cout << "测试1: ";
    for (int num : result1) {
        cout << num << " ";
    }
    cout << endl;

    // 测试2
    vector<int> nums3 = { 4, 9, 5 };
    vector<int> nums4 = { 9, 4, 9, 8, 4 };
    vector<int> result2 = solution.intersection(nums3, nums4);
    cout << " 测试2: ";
    for (int num : result2) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值