3 line Python Code

  • 5

    Ideas based on : zhiqing_xiao's Solution

    class Solution:
        # @param {integer[]} nums
        # @return {integer[]}
        def singleNumber(self, nums):
            xor = reduce(operator.xor, nums)
            ans = reduce(operator.xor, filter(lambda x : x & xor & -xor, nums))
            return [ans, ans ^ xor]

    Detailed explanations : leetcode-single-number-iii in my blog (in Chinese)

  • 3

    A bit shorter and faster:

    ans = reduce(operator.xor, (x for x in nums if x & xor & -xor))

    The speed difference isn't noticeable with the given inputs, but you can see it like this (about 384 ms for the generator, about 504 ms for the filter+lambda)

    for _ in range(100):
        ans = reduce(operator.xor, (x for x in nums if x & xor & -xor))

    More lines but actually fewer printable characters and even faster (about 293 ms):

        ans = 0
        for x in nums:
            if x & xor & -xor:
                ans ^= x

    All times are averages of three submissions each.

  • 0

    yup, (x for x in nums if x & xor & -xor) is more efficient than filter function :D

  • 0

    Nice code, good example of reduce, filter, lambda clauses in Python!

Log in to reply

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