zoukankan      html  css  js  c++  java
  • 两个数组的交集

    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;
        }
    };
  • 相关阅读:
    洛谷 简单字符串 'P1055ISBN号码' 问题
    P1424
    洛谷训练P1008(循环+暴力)
    C语言中一些知识点
    二叉树的基本功能实现方法(C++)
    值传递,引用传递,指针传递
    istringstream、ostringstream、stringstream类介绍
    类模板的友元
    C++ 标准库和标准模板库(STL)
    常用数据类型对应字节数
  • 原文地址:https://www.cnblogs.com/Bipolard/p/9994254.html
Copyright © 2011-2022 走看看