Wednesday 12 October 2022

Array - 350. Intersection of Two Arrays II

#===================================
# Tanzila Islam
# Email: tanzilamohita@gmail.com
# Language: Python 3
#===================================

# Method - 1
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        intersec = []

        i = 0
        j = 0

        nums1.sort()
        nums2.sort()

        while(i<len(nums1) and j<len(nums2)):
            if nums1[i] == nums2[j]:
                intersec.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return intersec


# Method - 2
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        intersec = []

        dict = {}
        for n in nums1:
            if n in dict:
                dict[n] += 1
            else: 
                dict[n] = 1
        # print(dict)
        for n in nums2:
            if n in dict and dict[n]>0:
                dict[n] -= 1
                intersec.append(n)

        return intersec

No comments:

Post a Comment