leetCode 350. Intersection of Two Arrays II 哈希

简介:

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.

  • The result can be in any order.


Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?

  • What if nums1's size is small compared to nums2's size? Which algorithm is better?

  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

题目大意:

找出两个数组中相同元素,相同元素的个数可以大于1.

思路:

将数组2的元素放入multiset中。

遍历数组1,如果在multiset找到与数组1相等的元素,将该元素放入结果数组中,在multiset中删除第一个和这个元素相当的元素。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class  Solution {
public :
     vector< int > intersect(vector< int >& nums1, vector< int >& nums2) {
         vector< int > result;
         multiset< int > set2;
         for ( int  i = 0; i < nums2.size(); i++)
             set2.insert(nums2[i]);
         for ( int  i = 0; i < nums1.size(); i++)
         {
             if (set2.find(nums1[i]) != set2.end())
             {
                 result.push_back(nums1[i]);
                 set2.erase(set2.find(nums1[i]));
             }
         }
         return  result;
     }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837559
相关文章
|
2月前
《LeetCode》—— 哈希
《LeetCode》—— 哈希
|
4月前
leetcode-1044:最长重复子串(滚动哈希)
leetcode-1044:最长重复子串(滚动哈希)
28 0
|
15天前
[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大数的方法。
16 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中是否存在
78 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

热门文章

最新文章