leetCode 349. Intersection of Two Arrays 哈希

简介:

349. Intersection of Two Arrays

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.

题目大意:

将两个数组中一样的元素存入结果数组返回。结果数组中的元素不能重复。

思路:

1.将数组1,数组2分别放入set中去重。

2.使用迭代器iterator遍历set1,在set2中找与set1相同的元素,找到就添加到结果数组中。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class  Solution {
public :
     vector< int > intersection(vector< int >& nums1, vector< int >& nums2) {
         vector< int  > result;
         set< int > set1;
         set< int > set2;
         set< int >::iterator it;
         
         for ( int  i = 0 ; i < nums1.size();i++)
             if (set1.find(nums1[i]) == set1.end())
                 set1.insert(nums1[i]);
         for ( int  i = 0 ; i < nums2.size();i++)
             if (set2.find(nums2[i]) == set2.end())
                 set2.insert(nums2[i]);
         for (it = set1.begin();it != set1.end();it++)
         {
             if (set2.find(*it) != set2.end() )
                 result.push_back(*it);
         }
         
         return  result;
     }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837597
相关文章
|
2月前
《LeetCode》—— 哈希
《LeetCode》—— 哈希
|
2月前
leetcode-1044:最长重复子串(滚动哈希)
leetcode-1044:最长重复子串(滚动哈希)
48 0
|
10月前
|
存储 缓存 算法
LeetCode刷题---Two Sum(一)
LeetCode刷题---Two Sum(一)
|
1月前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
1月前
|
存储 SQL 算法
LeetCode 题目 87:递归\动态规划\哈希实现 扰乱字符串
LeetCode 题目 87:递归\动态规划\哈希实现 扰乱字符串
|
2月前
[leetcode] 705. 设计哈希集合
[leetcode] 705. 设计哈希集合
|
2月前
leetcode-1001:网格照明(自定义哈希集合)
leetcode-1001:网格照明(自定义哈希集合)
27 0
|
8月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
20 0
|
10月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers