【LeetCode 350】 两个数组的交集 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?

解题思路

遍历元素少的list,然后将两个list中都存在的元素存入新list,返回。

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
   def intersect(self, nums1, nums2):
       """
      :type nums1: List[int]
      :type nums2: List[int]
      :rtype: List[int]
      """
       num = list()
       small_list = nums1
       large_list = nums2
       if len(nums1) > len(nums2):
           small_list = nums2
           large_list = nums1
       for i in range(len(small_list)):
           if small_list[i] in large_list:
               num.append(small_list[i])
               large_list.remove(small_list[i])

       return num
黄小豆 wechat
关注我的公众号,同步推送博客内容
坚持原创技术分享,您的支持将鼓励我继续创作!
0%