Three Python Solutions


  • 11
    L

    two pointers:

    class Solution(object):
        def intersect(self, nums1, nums2):
    
            nums1, nums2 = sorted(nums1), sorted(nums2)
            pt1 = pt2 = 0
            res = []
    
            while True:
                try:
                    if nums1[pt1] > nums2[pt2]:
                        pt2 += 1
                    elif nums1[pt1] < nums2[pt2]:
                        pt1 += 1
                    else:
                        res.append(nums1[pt1])
                        pt1 += 1
                        pt2 += 1
                except IndexError:
                    break
    
            return res
    

    use dictionary to count:

    class Solution(object):
        def intersect(self, nums1, nums2):
    
            counts = {}
            res = []
    
            for num in nums1:
                counts[num] = counts.get(num, 0) + 1
    
            for num in nums2:
                if num in counts and counts[num] > 0:
                    res.append(num)
                    counts[num] -= 1
    
            return res
    

    use Counter to make it cleaner:

    class Solution(object):
        def intersect(self, nums1, nums2):
    
            counts = collections.Counter(nums1)
            res = []
    
            for num in nums2:
                if counts[num] > 0:
                    res += num,
                    counts[num] -= 1
    
            return res

  • 0
    V
    This post is deleted!

  • 0
    L

    @vivian16 res is a list and num is an int, you can't use + operator between a list and an int. However, you can concatenate a list and a tuple. num, repensents a tuple, where its first element is num and second element is nothing.


Log in to reply
 

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