使用位运算符查找在数组中只出现一次的数字

Find the number that is present in array only once using bitwise operators

本文关键字:数字 一次 运算符 查找 数组      更新时间:2023-10-16

如果有一个数组,其中包含在该数组中出现两次的数字和一个只出现一次的数字,我们可以使用异或运算符来找到它,因为它符合共通律。如

1 2 3 2 3 
1 ^ 2 ^ 3 ^ 2 ^ 3 = ( 2 ^ 2 ) ^ ( 3 ^ 3 ) ^ 1 = 1

但是我们能不能用位技巧来找到数组中只出现一次的数字而其他数字可以出现n次,n> 1 ?

有一种方法可以做到这一点,但不是使用二进制操作符。您可以将每个数字表示为位向量,然后使用sum (mod n)将所有向量相加。结果向量将表示该唯一数字。

例如,让我们考虑n=3和序列2 3 5 2 5 5 2

向量为:[0 1 0], [0 1 1], [1 0 1], [0 1 0], [1 0 1], [1 0 1], [0 1 0]

所有向量的每元素和为:[3 4 4]

Mod 3将是:[0 1 1],相当于序列中唯一的元素。

这是异或技巧的推广;实际上异或就是这样的操作——对mod 2进行求和。

对于位运算符,不,除非n总是偶数。

但是还有很多其他方法可以使用,比如对出现一次的项进行排序和扫描,或者如果输入域受到某种限制,则将每个项分配给bucket。

作为第一个例子:

def findASingle(list):
    if list length is zero:
        return nothing
    if list length is one:
        return first item in list
    sort list
    for each item in last other than first and last:
        if item is different to both previous and next item:
            return item

对于第二个,假设它仅限于(例如)个位数非负整数:

def findASingle(list):
    create count[0..9], all set to zero
    for each item in last:
        count[item] = count[item] + 1
    for each index 0 through 9 inclusive:
        if count[index] is 1:
            return index
    return nothing