Leetcode #350 Intersection of Two Arrays II

Description

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

Note

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Explain

扫一遍nums1,然后每个元素去nums2中寻找并去除,时间复杂度O(nm^2) n为nums1长度,m为nums2长度,题目中有几个Follow up:
- 如果是有序的,那么开两个位置指示器,nums1前进的时候看nums2的指示器数是否相同或小于nums1所指示的数,当然相同的时候要记录,然后向前进,这样复杂度是O(n+m)
- 如果nums1的长度小于nums2,那就扫nums2去找nums1,复杂度不变
- 如果数过多无法一次读到内存,开两个dict记录每个数次数,分次读完后再扫一遍

Code

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        ans = []
        for i in nums1:
            if i in nums2:
                ans.append(i)
                nums2.remove(i)
        return ans

你可能感兴趣的:(leetcode,leetcode)