[英]Find the number that is present in array only once using bitwise operators
如果我们有一个数组,其中包含在其中出现两次的数字,以及一个只在其中出现一次的数字,则我们可以使用XOR运算符来找到它,因为它遵循相乘律。 例如
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]
等于3-序列中的唯一元素。
这是XOR技巧的概括; 实际上XOR正是此操作-mod 2中的求和。
对于按位运算符,不,除非n
始终为偶数。
但是,还有许多其他方法可以使用,例如对发生一次的项目进行排序和扫描,或者如果输入域受到某种限制,则将每个项目分配给存储桶。
作为第一个示例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.