A dictionary based solution in python


  • 15
    N

    class Solution(object):

    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        dict1 = dict()
        for i in nums1:
            if i not in dict1:
                dict1[i] = 1
            else:
                dict1[i] += 1
        ret = []
        for i in nums2:
            if i in dict1 and dict1[i]>0:
                ret.append(i)
                dict1[i] -= 1
        return ret

  • 0
    J

    Solid solution. I was going to create multiple dictionaries and then cross reference to find the minimum value for a given key between the two, but takes less space/time. Much more elegant.


  • 2
    H

    bangbangda

    You are here! 
    Your runtime beats 99.92% of pythonsubmissions.
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.