[Leetcode] 349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.
Example:Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
Each element in the result must be unique.
The result can be in any order.

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> shortSet;
        set<int> returnSet;
        vector<int> ret;
        
        if(nums1.size() > nums2.size()){
            vector<int> tmp = nums1;
            nums1 = nums2;
            nums2 = tmp;
        }
        
        for(auto i = nums1.begin(); i != nums1.end(); i++){
            shortSet.insert(*i);
        }
        for(auto i = nums2.begin(); i != nums2.end(); i++){
            if(shortSet.count(*i) > 0){
                returnSet.insert(*i);
            }
        }
        for(auto i = returnSet.begin(); i != returnSet.end(); i++){
            ret.push_back(*i);
        }
        return ret;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Given two arrays, write a function to compute their inter...
    六尺帐篷阅读 3,493评论 0 1
  • LeetCode题目链接 注意:凡是以英文出现的,都是题目提供的,包括答案代码里的前几行。 题目: Given t...
    _Xie_阅读 1,310评论 0 0
  • 前情回顾:渣男日记(七) 回到学校,说不上是高兴还是失落,或是其他什么心情。 那晚,我们一寝室的兄弟们出去吃了一顿...
    听任蔓草湮路阅读 5,027评论 1 1
  • 我文学天赋基本没有,在泥土里滚打大半辈子了!也有学习的心意,不懂什么是文学,只知道有时候胡攥。不过有些道理还是懂的...
    元三利阅读 1,549评论 0 1
  • 一如昨日 月朗星稀 圆圆的月 诉说团圆 一如当日 明朗星空 蓝蓝的天 飘远思念 一如过去的每一年 秋季的气息迎面扑...
    夏荷梦阅读 1,711评论 3 3

友情链接更多精彩内容