Leetcode # 350. Intersection of Two Arrays II

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

Solution

Time Complexity: O(len(nums1) + len(nums2))
Space Complexity: O(len(nums1) + len(nums2))

class Solution:
  def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
    nums = [collections.Counter(), collections.Counter()]
    for i in range(2):
      for num in [nums1, nums2][i]:
        nums[i][num] += 1

    intersection = []
    for num in (nums[0].keys() & nums[1].keys()):
      intersection += [num] * min(nums[0][num], nums[1][num])
    
    return intersection

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami