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》—— 哈希
|
4月前
leetcode-1044:最长重复子串(滚动哈希)
leetcode-1044:最长重复子串(滚动哈希)
28 0
|
16天前
[leetcode] 705. 设计哈希集合
[leetcode] 705. 设计哈希集合
|
4月前
leetcode-1001:网格照明(自定义哈希集合)
leetcode-1001:网格照明(自定义哈希集合)
20 0
|
6月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
17 0
|
算法 索引
leetcode-每日一题745. 前缀和后缀搜索(哈希和字典树)
如果我们用前缀 prefix 和 后缀 suff去暴力对比所有单词肯定会超时,我们可以先把单词里所有的前缀后缀组合,中间用特殊符号@连接,对应的最大下标存入哈希表中。搜索时,用特殊符号@连接前缀后缀,在哈希表中进行搜索
64 0
leetcode-每日一题745. 前缀和后缀搜索(哈希和字典树)
|
算法
leetcode-每日一题873. 最长的斐波那契子序列的长度(哈希和二分)
题目要求斐波那契数列长度要大于等于3,就等于说要确定 x[1] 和 x[2]来确定x[3]…x[n]之和的数列,所以我们用两层for循环来枚举x[1] 和 x[2] ,因为斐波那契数列满足 x[i] = x[i - 1] + x[i - 2], 所以x[3] = x[1] + x[2] x[4] = x[3] + x[2]…,我们只需要三个变量来不断变换, 每次从 arr 中找前两个数,然后查看后续在符合斐波那契的数在arr中是否存在
79 0
leetcode-每日一题873. 最长的斐波那契子序列的长度(哈希和二分)
|
算法
leetcode-每日一题648. 单词替换(哈希)
将字符串数组中的所有字符串存入哈希表中,遍历sentence中的所有单词,从短到长遍历单词前缀,对比哈希表中的单词是否存在,存在则替换。
51 0
leetcode-每日一题648. 单词替换(哈希)
|
存储 算法
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
LeetCode 350. Intersection of Two Arrays II
给定两个数组,编写一个函数来计算它们的交集。
47 0
LeetCode 350. Intersection of Two Arrays II

热门文章

最新文章