美文网首页
349. Intersection of Two Arrays

349. Intersection of Two Arrays

作者: 这就是一个随意的名字 | 来源:发表于2017-07-31 09:15 被阅读0次

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.

给定两个数组,计算它们的重复部分。
注意:返回结果中的元素不要重复,结果可以任意顺序组织。


思路:
利用关联容器set保存nums1的元素,对于nums2中的每个元素,检查是否在set中。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> m(nums1.begin(), nums1.end());
        vector<int> res;
        for (auto a : nums2)
            if (m.count(a)) {       //元素重复
                res.push_back(a);
                m.erase(a);         //已经计入的不再重复计算
            }
        return res;
    }
};
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for(int i=0;i<nums1.length;i++){
            set1.add(nums1[i]);
        }
        for(int i=0;i<nums2.length;i++){
            if(set1.contains(nums2[i])) set2.add(nums2[i]);
        }
        int[] res=new int[set2.size()];
        int i=0;
        for(int num:set2){
            res[i++]=num;
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:349. Intersection of Two Arrays

      本文链接:https://www.haomeiwen.com/subject/jiellxtx.html