[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 ...
随机推荐
- Linux的rwx
- 洛谷 P2722 总分题解
题目描述 我们可以从几个种类中选取竞赛的题目,这里的一个"种类"是指一个竞赛题目的集合,解决集合中的题目需要相同多的时间并且能得到相同的分数.你的任务是写一个程序来告诉USACO的 ...
- python为什么要使用闭包
为什么要使用闭包 闭包避免了使用全局变量,此外,闭包允许将函数与其所操作的某些数据(环境)关连起来.这一点与面向对象编程是非常类似的,在面对象编程中,对象允许我们将某些数据(对象的属性)与一个或者多个 ...
- asp.net 访问局域网共享文件
最近有个项目ASP.NET的项目,要读写一个局域网里的共享文件夹上的文件,记录如下: 1.访问共享文件 在这里我定义了一个方法,SaveFileExist(filesrc,filename),这个方法 ...
- Alpha冲刺(10/10)——追光的人
1.队友信息 队员学号 队员博客 221600219 小墨 https://www.cnblogs.com/hengyumo/ 221600240 真·大能猫 https://www.cnblogs. ...
- 项目Alpha冲刺--6/10
项目Alpha冲刺--6/10 作业要求 这个作业属于哪个课程 软件工程1916-W(福州大学) 这个作业要求在哪里 项目Alpha冲刺 团队名称 基于云的胜利冲锋队 项目名称 云评:高校学生成绩综合 ...
- PageHelper分页正确用法
依赖和配置就不说了,说用法 Page<Object> page = PageHelper.startPage(pageNum, pageSize); List<SysRoleDTO& ...
- djiango-异步发送邮件--celery
安装 pip install celery==4.2.0 # celery4.x支持django1.11以上版本 试了好几个版本 就4.2.0能发送成功 1.项目目录里新建一个celery的包cele ...
- Python 代码混淆和加密技术
动机 Python进行商业开发时, 需要有一定的安全意识, 为了不被轻易的逆向. 混淆和加密就有所必要了. 混淆 为了增加代码阅读的难度, 源代码的混淆非常必要, 一个在线的Python代码混淆网站. ...
- EF实体类指定部分属性不映射数据库标记
命名空间 ;using System.ComponentModel.DataAnnotations.Schema; 实体部分 public partial class Student { [NotMa ...