349. Intersection of Two Arrays

来源:互联网 发布:mac上顿号怎么打 编辑:程序博客网 时间:2024/05/10 15:06

题目:

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.
题意:

给定两个数组,写一个功能计算两者的交叉部分。

note:

1、结果集中的每一个元素必须唯一;

2、结果集可以是任何顺序


思路一:

将两个数组排序,之后逐个数进行对比,排除相同的元素。

代码:11ms

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {                sort(nums1.begin(), nums1.end());        sort(nums2.begin(), nums2.end());        int c1 = 0;        int c2 = 0;        vector<int> result;                while(c1<nums1.size() && c2<nums2.size()){            if(nums1[c1]==nums2[c2]){                if(!result.size() || result.back()!=nums1[c1]){                    result.push_back(nums1[c1]);                }                c1++;                c2++;            }else if(nums1[c1]>nums2[c2]){                c2++;            }else{                c1++;            }        }                return result;    }};
思路二:

借助set集合的元素不相同型完成相同元素的排除,之后直接比较两个数组之中的元素即可。

代码:8ms

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {                unordered_set<int> interSet(nums1.begin(), nums1.end());        vector<int> result;                for(auto num : nums2){            if(interSet.count(num)){                result.push_back(num);                interSet.erase(num);            }        }                return result;    }};

0 0
原创粉丝点击