Python solution with detailed explanation


  • 0
    G

    Solution

    Intersection of Two Arrays https://leetcode.com/problems/intersection-of-two-arrays/?tab=Description

    Algorithm

    • Use a set to store all numbers from nu1.
    • Then test membership of num2 in this set. Keep results in another set so that they are automatically deduped.
    class Solution(object):
        def intersection(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            nums1_set = set(nums1)
            result_set = set([])
            for x in nums2:
                if x in nums1_set and x not in result_set:
                    result_set.add(x)
            return [x for x in result_set]
    

Log in to reply
 

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