349. Intersection of Two Arrays
Posted whl-hl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了349. Intersection of Two Arrays相关的知识,希望对你有一定的参考价值。
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.
Tags: Binary Search Hash Table Two Pointers Sort
Similar Problems: (E) Intersection of Two Arrays II
2. 解题思路
- 求两个数组中公有的数字
- 利用STL中的集合SET实现
3. 代码
1 class Solution { 2 public: 3 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) 4 { 5 std::vector<int> tVec; 6 if (nums1.empty() || nums2.empty()) 7 { 8 return tVec; 9 } 10 std::set<int> tSet; 11 std::set<int> tResultSet; 12 for (int i=0; i<nums1.size(); i++) 13 { 14 tSet.insert(nums1.at(i)); 15 } 16 for (int i=0; i<nums2.size(); i++) 17 { 18 if (tSet.find(nums2.at(i)) != tSet.end()) 19 { 20 tResultSet.insert(nums2.at(i)); 21 } 22 } 23 std::set<int>::iterator it; 24 for(it = tResultSet.begin(); it != tResultSet.end(); it++) 25 { 26 tVec.push_back(*it); 27 } 28 return tVec; 29 } 30 };
4. 反思
以上是关于349. Intersection of Two Arrays的主要内容,如果未能解决你的问题,请参考以下文章
349. Intersection of Two Arrays
349. Intersection of Two Arrays
Leetcode 349. Intersection of Two Arrays
[leetcode]349.Intersection of Two Arrays