56 - the number of array numbers appearing I.

An array of integers  nums in addition to the two figures, other figures appear twice. Please write a program to find these two figures appear only. Required time complexity is O (n), the spatial complexity is O (1).

示例 1:

输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]

示例 2:

输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]

 

思路:利用异或运算^的特点
0和任何数异或等于该数
任何数和自身异或等于0
异或运算满足交换律
当将一个数组的数全部按位异或后,可以将成对的数放在前面先运算,而成对的数经过上述1,2会得到0,也就达到了消去成对的数的目的。
此时数组中剩下两个不同的数异或,得到的结果mask是这两个数不同的位上值为1,相同的为0.
但这样没办法把两个数分离出来。既然这两个不同的数必然有位是不同的,并且异或的结果也告诉我们哪些位不同。我们不妨以mask的最低的值为1的位(设为a0位)来区分这两个数,其中一个数a0位等于1,另一个等于0.
其中通过位运算x & (-x)得到a0 = 1,其他位为0的结果。
同样我们将数组中其他的数,也分成两组:a0 = 0组和a0 = 1组,这样保证了两个不同的数分在两组,也保证了成对的数必在其中一组而不会一对数分在两组。
再分别对两组的数进行异或运算,最后得到的两个数即所求。
class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        #一个数和0异或是其本身,和本身异或为0
        n1,n2=0,0
        #(1)计算整个数组的异或值
        xor_num=0
        for num in nums:
            xor_num^=num
        #(2)寻找xor_num从右数第一个为1的位置
        mask=1
        while xor_num&mask==0:
            mask<<=1
        #(3)分组求解两个只出现一次的数字n1,n2
        for num in nums:
            if num&mask==0:
                n1^=num
            else:
                n2^=num
        return [n1,n2]

  

Guess you like

Origin www.cnblogs.com/USTC-ZCC/p/12466180.html
Recommended