[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 ...
随机推荐
- KVM-virsh常用命令
virsh list #在线VM virsh list --all #所有VM virsh start #开机 virsh shutdown #软关机 virsh destroy #强制关机 virs ...
- 爬虫 - 请求库之requests
介绍 使用requests可以模拟浏览器的请求,比起python内置的urllib模块,requests模块的api更加便捷(本质就是封装了urllib3) 注意:requests库发送请求将网页内容 ...
- python完成加密参数sign计算并输出指定格式的字符串
加密规则: 1.固定加密字符串+字符串组合(key/value的形式,并通过aissc码排序), 2.通过sha1算法对排序后的字符串进行加密, 3.最终输出需要的参数sign 4.完成请求参数数据的 ...
- python -- 连接 orclae cx_Oracle的使用 二
转:https://www.cnblogs.com/cyxiaer/p/9396861.html 必需的Oracle链接库的下载地址:https://www.oracle.com/technetwor ...
- tensorflow2.0 学习(二)
线性回归问题 # encoding: utf-8 import numpy as np import matplotlib.pyplot as plt data = [] for i in range ...
- install_config
#! /bin/bash REPO='10.10.238.114:4507' zabbix='10.10.238.110' osmaster=`cat /etc/redhat-release |awk ...
- 洛谷 P2312 解方程 题解
P2312 解方程 题目描述 已知多项式方程: \[a_0+a_1x+a_2x^2+\cdots+a_nx^n=0\] 求这个方程在 [1,m][1,m] 内的整数解(\(n\) 和 \(m\) 均为 ...
- MongoDB---如何避免插入重复数据(pymongo)
以下摘自pymongo文档: update_one(filter, update, upsert=False) update_many(filter, update, upsert=False) fi ...
- Git常用命令及常见报错:You have not concluded your merge (MERGE_HEAD exists)、清理无效的远程追踪分支
一.常用命令 切换到master分支:git checkout master 查看已有本地及远程分支:git branch -a(先git pull拉下全部数据) 查看远程分支:git branch ...
- 洛谷P3620 [APIO/CTSC 2007] 数据备份
题目 贪心+堆. 一般贪心题用到堆的时候都会存在一种反悔操作,因此这个题也不例外. 首先电缆一定是连接两个相邻的点的,这很好证明,其次一个点只能被一条电缆连接,所以我们通过选这个电缆,不选相邻电缆和选 ...