350. Intersection of Two Arrays II

https://leetcode.com/problems/intersection-of-two-arrays-ii/

solution

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) > len(nums2): 
            return self.intersect(nums2, nums1)
            
        cnt = collections.Counter(nums1)
        ans = []
        for x in nums2:
            if cnt[x] > 0:
                ans.append(x)
                cnt[x] -= 1
        return ans

时间复杂度:O(m+n) 空间复杂度:O(n)

Last updated