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

Example 1:

  1. Input: nums1 = [1,2,2,1], nums2 = [2,2]
  2. Output: [2,2]

Example 2:

  1. Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  2. 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:

  1. class Solution(object):
  2. def intersect(self, nums1, nums2):
  3. """
  4. :type nums1: List[int]
  5. :type nums2: List[int]
  6. :rtype: List[int]
  7. """
  8. if len(nums1) > len(nums2):
  9. return self.intersect(nums2, nums1)
  10.  
  11. lookup = collections.defaultdict(int)
  12. for i in nums1:
  13. lookup[i] += 1
  14.  
  15. res = []
  16. for i in nums2:
  17. if lookup[i] > 0:
  18. res += i,
  19. lookup[i] -= 1
  20.  
  21. return res
  1. # If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
  2. # Time: O(min(m, n) * log(max(m, n)))
  3. # Space: O(1)
  4. # Binary search solution.
  5. class Solution(object):
  6. def intersect(self, nums1, nums2):
  7. """
  8. :type nums1: List[int]
  9. :type nums2: List[int]
  10. :rtype: List[int]
  11. """
  12. if len(nums1) > len(nums2):
  13. return self.intersect(nums2, nums1)
  14.  
  15. def binary_search(compare, nums, left, right, target):
  16. while left < right:
  17. mid = left + (right - left) / 2
  18. if compare(nums[mid], target):
  19. right = mid
  20. else:
  21. left = mid + 1
  22. return left
  23.  
  24. nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
  25.  
  26. res = []
  27. left = 0
  28. for i in nums1:
  29. left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
  30. if left != len(nums2) and nums2[left] == i:
  31. res += i,
  32. left += 1
  33.  
  34. return res
  1. # If the given array is already sorted, and the memory is limited or m ~ n.
  2. # Time: O(m + n)
  3. # Soace: O(1)
  4. # Two pointers solution.
  5. class Solution(object):
  6. def intersect(self, nums1, nums2):
  7. """
  8. :type nums1: List[int]
  9. :type nums2: List[int]
  10. :rtype: List[int]
  11. """
  12. nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
  13.  
  14. res = []
  15.  
  16. it1, it2 = 0, 0
  17. while it1 < len(nums1) and it2 < len(nums2):
  18. if nums1[it1] < nums2[it2]:
  19. it1 += 1
  20. elif nums1[it1] > nums2[it2]:
  21. it2 += 1
  22. else:
  23. res += nums1[it1],
  24. it1 += 1
  25. it2 += 1
  26.  
  27. return res
  1. # If the given array is not sorted, and the memory is limited.
  2. # Time: O(max(m, n) * log(max(m, n)))
  3. # Space: O(1)
  4. # Two pointers solution.
  5. class Solution(object):
  6. def intersect(self, nums1, nums2):
  7. """
  8. :type nums1: List[int]
  9. :type nums2: List[int]
  10. :rtype: List[int]
  11. """
  12. nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n)))
  13.  
  14. res = []
  15.  
  16. it1, it2 = 0, 0
  17. while it1 < len(nums1) and it2 < len(nums2):
  18. if nums1[it1] < nums2[it2]:
  19. it1 += 1
  20. elif nums1[it1] > nums2[it2]:
  21. it2 += 1
  22. else:
  23. res += nums1[it1],
  24. it1 += 1
  25. it2 += 1
  26.  
  27. return res

C++:

  1. // If the given array is not sorted and the memory is unlimited.
  2. // Time: O(m + n)
  3. // Space: O(min(m, n))
  4. // Hash solution.
  5. class Solution {
  6. public:
  7. vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
  8. if (nums1.size() > nums2.size()) {
  9. return intersect(nums2, nums1);
  10. }
  11.  
  12. unordered_map<int, int> lookup;
  13. for (const auto& i : nums1) {
  14. ++lookup[i];
  15. }
  16.  
  17. vector<int> result;
  18. for (const auto& i : nums2) {
  19. if (lookup[i] > 0) {
  20. result.emplace_back(i);
  21. --lookup[i];
  22. }
  23. }
  24.  
  25. return result;
  26. }
  27. };

C++:

  1. // If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
  2. // Time: O(min(m, n) * log(max(m, n)))
  3. // Space: O(1)
  4. // Binary search solution.
  5. class Solution {
  6. public:
  7. vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
  8. if (nums1.size() > nums2.size()) {
  9. return intersect(nums2, nums1);
  10. }
  11.  
  12. // Make sure it is sorted, doesn't count in time.
  13. sort(nums1.begin(), nums1.end());
  14. sort(nums2.begin(), nums2.end());
  15.  
  16. vector<int> result;
  17. auto it = nums2.cbegin();
  18. for (const auto& i : nums1) {
  19. it = lower_bound(it, nums2.cend(), i);
  20. if (it != nums2.end() && *it == i) {
  21. result.emplace_back(*it++);
  22. }
  23. }
  24.  
  25. return result;
  26. }
  27. };

C++:

  1. // If the given array is already sorted, and the memory is limited or m ~ n.
  2. // Time: O(m + n)
  3. // Soace: O(1)
  4. // Two pointers solution.
  5. class Solution {
  6. public:
  7. vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
  8. vector<int> result;
  9. // Make sure it is sorted, doesn't count in time.
  10. sort(nums1.begin(), nums1.end());
  11. sort(nums2.begin(), nums2.end());
  12. auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
  13. while (it1 != nums1.cend() && it2 != nums2.cend()) {
  14. if (*it1 < *it2) {
  15. ++it1;
  16. } else if (*it1 > *it2) {
  17. ++it2;
  18. } else {
  19. result.emplace_back(*it1);
  20. ++it1, ++it2;
  21. }
  22. }
  23. return result;
  24. }
  25. };

C++:

  1. // If the given array is not sorted, and the memory is limited.
  2. // Time: O(max(m, n) * log(max(m, n)))
  3. // Space: O(1)
  4. // Two pointers solution.
  5. class Solution {
  6. public:
  7. vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
  8. vector<int> result;
  9. // O(max(m, n) * log(max(m, n)))
  10. sort(nums1.begin(), nums1.end());
  11. sort(nums2.begin(), nums2.end());
  12. auto it1 = nums1.cbegin(), it2 = nums2.cbegin();
  13. while (it1 != nums1.cend() && it2 != nums2.cend()) {
  14. if (*it1 < *it2) {
  15. ++it1;
  16. } else if (*it1 > *it2) {
  17. ++it2;
  18. } else {
  19. result.emplace_back(*it1);
  20. ++it1, ++it2;
  21. }
  22. }
  23. return result;
  24. }
  25. };

  

类似题目:

[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的更多相关文章

  1. LeetCode 349. Intersection of Two Arrays (两个数组的相交)

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  2. 26. leetcode 350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...

  3. [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 ...

  4. [LeetCode] Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  5. [LintCode] Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection.Notice Each element in the result s ...

  6. LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  7. LeetCode 350. Intersection of Two Arrays II

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  8. Python [Leetcode 350]Intersection of Two Arrays II

    题目描述: Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, ...

  9. [LeetCode] 349. Intersection of Two Arrays 两个数组相交

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

随机推荐

  1. KVM-virsh常用命令

    virsh list #在线VM virsh list --all #所有VM virsh start #开机 virsh shutdown #软关机 virsh destroy #强制关机 virs ...

  2. 爬虫 - 请求库之requests

    介绍 使用requests可以模拟浏览器的请求,比起python内置的urllib模块,requests模块的api更加便捷(本质就是封装了urllib3) 注意:requests库发送请求将网页内容 ...

  3. python完成加密参数sign计算并输出指定格式的字符串

    加密规则: 1.固定加密字符串+字符串组合(key/value的形式,并通过aissc码排序), 2.通过sha1算法对排序后的字符串进行加密, 3.最终输出需要的参数sign 4.完成请求参数数据的 ...

  4. python -- 连接 orclae cx_Oracle的使用 二

    转:https://www.cnblogs.com/cyxiaer/p/9396861.html 必需的Oracle链接库的下载地址:https://www.oracle.com/technetwor ...

  5. tensorflow2.0 学习(二)

    线性回归问题 # encoding: utf-8 import numpy as np import matplotlib.pyplot as plt data = [] for i in range ...

  6. install_config

    #! /bin/bash REPO='10.10.238.114:4507' zabbix='10.10.238.110' osmaster=`cat /etc/redhat-release |awk ...

  7. 洛谷 P2312 解方程 题解

    P2312 解方程 题目描述 已知多项式方程: \[a_0+a_1x+a_2x^2+\cdots+a_nx^n=0\] 求这个方程在 [1,m][1,m] 内的整数解(\(n\) 和 \(m\) 均为 ...

  8. MongoDB---如何避免插入重复数据(pymongo)

    以下摘自pymongo文档: update_one(filter, update, upsert=False) update_many(filter, update, upsert=False) fi ...

  9. Git常用命令及常见报错:You have not concluded your merge (MERGE_HEAD exists)、清理无效的远程追踪分支

    一.常用命令 切换到master分支:git checkout master 查看已有本地及远程分支:git branch -a(先git pull拉下全部数据) 查看远程分支:git branch ...

  10. 洛谷P3620 [APIO/CTSC 2007] 数据备份

    题目 贪心+堆. 一般贪心题用到堆的时候都会存在一种反悔操作,因此这个题也不例外. 首先电缆一定是连接两个相邻的点的,这很好证明,其次一个点只能被一条电缆连接,所以我们通过选这个电缆,不选相邻电缆和选 ...