Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

 

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
[1,1,2]=>1 xor 1 xor 2=2
[1, 2, 1, 3, 2, 5]=> all xor= 3 & 5 != 0 => 0x11 xor 0x101=bit 2,3 is not equal=>find bit2 and seperate like [1,1,2]
        """
        r = 0
        for num in nums:
            r = r ^ num
        assert r != 0
        n = r & (~(r-1))
        ans1, ans2 = 0, 0
        for num in nums:
            if num & n == 0:
                ans1 = ans1 ^ num
            else:
                ans2 = ans2 ^ num
        return ans1, ans2
        

 

转载于:https://www.cnblogs.com/bonelee/p/5944192.html

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐