Python3 using set, 1 line.


  • 0
    W

    My first idea is using set, so here's the code:

    class Solution:
        def findDisappearedNumbers(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            return list(set(range(1, len(nums)+1)).difference(nums))
            
            
    

    Similar to some posts actually, though I use the .difference.

    And here's timing on my machine:

    >>> L = set(range(1, 21))
    >>> l = list(range(1, 21))
    >>> for _ in range(8):
    ...     l[random.randint(0, 20)] = random.choice(l)
    ... 
    >>> list(L.difference(l))
    [1, 5, 6, 8, 9]
    >>> setup = 'from __main__ import L, l'
    >>> timeit.timeit('list(i for i in L if i not in l)', setup)
    5.633241865177865
    >>> timeit.timeit('list(L.difference(l))', setup)
    1.3220966504792386
    >>> timeit.timeit('list(L-set(l))', setup)
    1.330732515692148
    >>> timeit.timeit('list(L^set(l))', setup)
    1.3967739521546036
    

Log in to reply
 

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