标签:
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
标签:
原文地址:http://www.cnblogs.com/bonelee/p/5944192.html