[LeetCode] 350. Intersection of Two Arrays II 两个数组相交II
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
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:Hashmap
解法2:双指针
Python:
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1) lookup = collections.defaultdict(int)
for i in nums1:
lookup[i] += 1 res = []
for i in nums2:
if lookup[i] > 0:
res += i,
lookup[i] -= 1 return res
# If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
# Time: O(min(m, n) * log(max(m, n)))
# Space: O(1)
# Binary search solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1) def binary_search(compare, nums, left, right, target):
while left < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid + 1
return left nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. res = []
left = 0
for i in nums1:
left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
if left != len(nums2) and nums2[left] == i:
res += i,
left += 1 return res
# If the given array is already sorted, and the memory is limited or m ~ n.
# Time: O(m + n)
# Soace: O(1)
# Two pointers solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. res = [] it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if nums1[it1] < nums2[it2]:
it1 += 1
elif nums1[it1] > nums2[it2]:
it2 += 1
else:
res += nums1[it1],
it1 += 1
it2 += 1 return res
# If the given array is not sorted, and the memory is limited.
# Time: O(max(m, n) * log(max(m, n)))
# Space: O(1)
# Two pointers solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n))) res = [] it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if nums1[it1] < nums2[it2]:
it1 += 1
elif nums1[it1] > nums2[it2]:
it2 += 1
else:
res += nums1[it1],
it1 += 1
it2 += 1 return res
C++:
// If the given array is not sorted and the memory is unlimited.
// Time: O(m + n)
// Space: O(min(m, n))
// Hash solution.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return intersect(nums2, nums1);
} unordered_map<int, int> lookup;
for (const auto& i : nums1) {
++lookup[i];
} vector<int> result;
for (const auto& i : nums2) {
if (lookup[i] > 0) {
result.emplace_back(i);
--lookup[i];
}
} return result;
}
};
C++:
// If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
// Time: O(min(m, n) * log(max(m, n)))
// Space: O(1)
// Binary search solution.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return intersect(nums2, nums1);
} // Make sure it is sorted, doesn't count in time.
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end()); vector<int> result;
auto it = nums2.cbegin();
for (const auto& i : nums1) {
it = lower_bound(it, nums2.cend(), i);
if (it != nums2.end() && *it == i) {
result.emplace_back(*it++);
}
} return result;
}
};
C++:
// If the given array is already sorted, and the memory is limited or m ~ n.
// Time: O(m + n)
// Soace: O(1)
// Two pointers solution.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
// Make sure it is sorted, doesn't count in time.
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
while (it1 != nums1.cend() && it2 != nums2.cend()) {
if (*it1 < *it2) {
++it1;
} else if (*it1 > *it2) {
++it2;
} else {
result.emplace_back(*it1);
++it1, ++it2;
}
}
return result;
}
};
C++:
// If the given array is not sorted, and the memory is limited.
// Time: O(max(m, n) * log(max(m, n)))
// Space: O(1)
// Two pointers solution.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
// O(max(m, n) * log(max(m, n)))
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
while (it1 != nums1.cend() && it2 != nums2.cend()) {
if (*it1 < *it2) {
++it1;
} else if (*it1 > *it2) {
++it2;
} else {
result.emplace_back(*it1);
++it1, ++it2;
}
}
return result;
}
};
类似题目:
[LeetCode] 349. Intersection of Two Arrays 两个数组相交
[LeetCode] 160. Intersection of Two Linked Lists 求两个链表的交集
All LeetCode Questions List 题目汇总
[LeetCode] 350. Intersection of Two Arrays II 两个数组相交II的更多相关文章
- LeetCode 349. Intersection of Two Arrays (两个数组的相交)
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- 26. leetcode 350. Intersection of Two Arrays II
350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...
- [LeetCode] 350. Intersection of Two Arrays II 两个数组相交之二
Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...
- [LeetCode] Intersection of Two Arrays II 两个数组相交之二
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- [LintCode] Intersection of Two Arrays II 两个数组相交之二
Given two arrays, write a function to compute their intersection.Notice Each element in the result s ...
- LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- LeetCode 350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- Python [Leetcode 350]Intersection of Two Arrays II
题目描述: Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, ...
- [LeetCode] 349. Intersection of Two Arrays 两个数组相交
Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...
随机推荐
- qt事件机制(转)
学习了一段时间的Qt之后,发现Qt的事件机制和其他语言的机制有些不同.Qt除了能够通过信号和槽机制来实现一些Action动作之外,还可以用对象所带的事件,或者用户自定义的事件来实现对象的一些行为处理. ...
- 事件类型(onchange)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 持续集成学习1 gitlab和jenkins安装
一.gitlab安装参照链接 https://www.cnblogs.com/linuxk/p/10100431.html 二.安装jenkins 1.获取jenkins源码包 https://blo ...
- Python爬虫 | re正则表达式解析html页面
正则表达式(Regular Expression)是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为"元字符"). 正则表达式通常被用来匹配.检索.替换和 ...
- 洛谷P3534 [POI2012] STU
题目 二分好题 首先用二分找最小的绝对值差,对于每个a[i]都两个方向扫一遍,先都改成差满足的形式,然后再找a[k]等于0的情况,发现如果a[k]要变成0,则从他到左右两个方向上必会有两个连续的区间也 ...
- pycharm2018.2.1破解、汉化
##我只是一个搬运工 -_- (一)先破解,破解教程直接给个网址吧,感谢各位大神的无私奉献:https://blog.csdn.net/u014044812/article/details/78 ...
- 转载:理解scala中的Symbol
相信很多人和我一样,在刚接触Scala时,会觉得Symbol类型很奇怪,既然Scala中字符串都是不可变的,那么Symbol类型到底有什么作用呢? 简单来说,相比较于String类型,Symbol类型 ...
- Hadoop综合大作业总评
作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3363 1.把python爬取的数据传到linux 2.把数据的逗号代替为 ...
- 【数值分析】Python实现Lagrange插值
一直想把这几个插值公式用代码实现一下,今天闲着没事,尝试尝试. 先从最简单的拉格朗日插值开始!关于拉格朗日插值公式的基础知识就不赘述,百度上一搜一大堆. 基本思路是首先从文件读入给出的样本点,根据输入 ...
- 如何利用IIS调试ASP.NET网站程序详解
如何利用IIS调试ASP.NET网站程序详解 更新时间:2019年01月13日 08:44:13 作者:江湖逍遥 我要评论 这篇文章主要给大家介绍了关于如何利用IIS调试ASP.NET网 ...