我有两个整数,让我们称它们为haystack
和needle
.我需要判断一下,如果needle
的二进制表示出现在haystack
[OPTIONALLY找到第一个出现的位置]
示例
haystack = 0b10101111010110010101010101110
needle = 0b1011001 # occurred in position 13
needle = 0b111011 # not occurred
我在寻找最低可能的时间复杂度,我不能写一个时间复杂度超过O(h)
的代码,其中h
是大海捞针中的比特数.您可以在下面看到我的代码.
我需要判断预定义的needle
(它永远不会改变,它是一个odd数字)在数十亿个随机的haystack
整数中出现(所以我们不能对haystack
进行预处理以优化速度)
由于查找位置是可选的,如果您可以编写一段时间复杂度更高的代码,只返回一个指示发生的布尔值,那么它也是完美的.因为在数十亿次判断中,我知道它没有发生,当它发生时,我可以使用以下代码找到位置.
一个有假阳性结果的好的概率算法也是可以的.
def find_needle_in_haystack(haystack, needle):
n = needle.bit_length() # calculate the number of bits in needle
mask = (1 << n) - 1 # create a mask with n bits
i = 0
while haystack != 0:
x = haystack & mask # bitwise AND with mask to get first n bits
if x == needle:
return i
i += 1
haystack >>= 1 # shift haystack to the right by 1 bit
return -1 # needle not found in haystack