• 两个数组的交集


    Given two arrays, write a function to compute their intersection.

    Example 1:

    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2]
    

    Example 2:

    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [9,4]

    Note:

    • Each element in the result must be unique.
    • The result can be in any order.

     题意:求两个数组的交集,交集中的元素是唯一的,可以是任意顺序。

    思路:利用哈希集合,首先将数组1的值插入到哈希集合中,利用哈希集合自动去重,然后遍历数组2,如果这个元素在哈希集合中出现过,那么就存入到结果数组中,这里要注意,把哈希集合中的该元素也要删除(不然如果后面数组2还有相同的元素,就又加入到结果数组了,结果数组就会有元素重复)。

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            unordered_set<int> hashset;
            int len=nums1.size();
            vector<int> ans(len,0);  //开始声明了大小,赋值了,后面记得重新设置大小
            for(int i=0;i<len;i++){  //把nums1放入hashset,自动去掉重复了
                hashset.insert(nums1[i]);
            }
            int n=0;          //nums2与hashset比较,count=1就保存到答案,并且把hashset中的那个键值给去掉
            for(int i=0;i<nums2.size();i++){
                if(hashset.count(nums2[i])!=0){
                    ans[n++]=nums2[i];
                    hashset.erase(nums2[i]);
                }
            }
            ans.resize(n);
            return ans;
        }
    };
  • 相关阅读:
    在Android中如何获取视频的第一帧图片并显示在一个ImageView中
    利用MsChart控件绘制多曲线图表 z
    国外成熟的程序交易系统的思路 z
    稳健获利
    用vmware安装gho文件
    数学之美 zt
    大型邮箱smtp服务器及端口 收集
    英语之路 zt
    C# Get Desktop Screenshot ZZ
    C#/PHP Compatible Encryption (AES256) ZZ
  • 原文地址:https://www.cnblogs.com/Bipolard/p/9994254.html
Copyright © 2020-2023  润新知