[leetcode]: 349. Intersection of Two Arrays

来源:互联网 发布:debian 软件源配置 编辑:程序博客网 时间:2024/05/23 00:07

1.题目描述

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.

翻译:求两个数组的交集。要求:结果中的元素是唯一的,不限定元素顺序。

2.分析

可以借助c++的set容器,或python的set对象。

3.代码

python

def intersection(self,nums1, nums2):    return list(set(nums1)&set(nums2))

c++

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {    unordered_set<int> set1(nums1.begin(), nums1.end());    vector<int> result;    for (int n : nums2) {        if (set1.erase(n))//元素在set1中            result.push_back(n);    }    return result;}
0 0