[leetcode]: 349. Intersection of Two Arrays

梦里梦外; 2022-06-15 21:29 254阅读 0赞

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

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

c++

  1. vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
  2. unordered_set<int> set1(nums1.begin(), nums1.end());
  3. vector<int> result;
  4. for (int n : nums2) {
  5. if (set1.erase(n))//元素在set1中
  6. result.push_back(n);
  7. }
  8. return result;
  9. }

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读