Python code, 3 lines using set


  • 21
    class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1=set(nums1)
        nums2=set(nums2)
        return list(nums1&nums2)

  • 15
    R

    make it 1 :)

    def intersection(self, nums1, nums2):
            return list(set(nums1) & set(nums2))

  • 0
    C

    this is a good answer, I don't know why some one vote down.


  • 0
    Z

    class Solution(object):
    def intersection(self, nums1, nums2):

        i = []
    
        for k in nums1:
            if k in nums2 and k not in i:
                i.append(k)
        
        return i

  • 10
    H

    @cheffyu because this answer just used the python implementation of intersection, it is same as

    return  set(nums2).intersection(nums2)
    

    If you do this during interview, it would definitely not impress the interviewer.


  • 0
    L

    @cheffyu
    I think the reason is that this is not an algorithm solution. The "intersection" operation of two arrays ("lists" here in Python) should be IMPLEMENTED, rather then USED. The problems here we are working on are under the topic of "Algorithm", and this solution just uses the built-in (it's good, but it's not the wanted one). If Python can use all its built-in and libraries, many hard problems here is not a real problem.


  • 0

    Make it 0 line :)

    intersection = lambda *p: list(set(p[1]) & set(p[2]))

  • 0
    A
    This post is deleted!

Log in to reply
 

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