使用位运算符查找在数组中只出现一次的数字
Find the number that is present in array only once using bitwise operators
如果有一个数组,其中包含在该数组中出现两次的数字和一个只出现一次的数字,我们可以使用异或运算符来找到它,因为它符合共通律。如
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
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- 如何使用Mersenne Twister生成两个数字之间的所有值一次
- 如何一次读取一个数字并将其存储在数组中,跳过重复项
- 一次打印 2 个字节的十六进制数字
- 生成一个rand()%25,其中每个数字只能出现一次
- c++将输出(数字)保存到一个数组中.一次两个数字
- 使用位运算符查找在数组中只出现一次的数字
- 找出一个数组中是否至少有一次从1到K的所有数字
- 一个数字只出现一次
- c++ rand()每个数字只使用一次