代码挑战:如何实现O(1)时间复杂度的区间分割偏移函数?
实现O(1)时间复杂度的区间分割偏移量计算函数
规律总结
通过枚举分割次数与对应偏移量的关系,我们可以推导出直接计算的数学规律:
- index=1 → 0.5 = 1/2
- index=2 → 0.75 = 3/4
- index=3 → 0.25 = 1/4
- index=4 → 0.875 =7/8
- index=5 →0.625=5/8
- index=6 →0.375=3/8
- index=7 →0.125=1/8
核心规律:
- 令
n为index的二进制位数(即n = index.bit_length()),例如index=3(二进制11)的n=2,index=5(二进制101)的n=3。 - 偏移量的分子为
2^(n+1) - 2*index -1,分母为2^n。 - 最终偏移量 = 分子 / 分母。
公式逻辑
这个公式对应题目中的分割规则:每次选最大区间,相同大小优先选最右侧。等价于在每一层(对应n位二进制的分割次数范围),从最右侧区间开始向左依次分割,分割点的二进制小数是对index在当前层的偏移量k = index - 2^(n-1)的二进制位取反后的数值。通过数学转换,取反操作可直接转化为上述公式,避免了循环处理,实现O(1)时间复杂度。
代码实现(Python)
def get_last_split_offset(index): if index <= 0: return 0.0 # 分割0次时返回0,可根据需求调整 n = index.bit_length() numerator = (1 << (n + 1)) - 2 * index - 1 denominator = 1 << n return numerator / denominator
验证
代入测试用例:
- index=1:
(4 - 2 -1)/2 =1/2=0.5✔️ - index=2:
(8-4-1)/4=3/4=0.75✔️ - index=7:
(16-14-1)/8=1/8=0.125✔️
所有结果均符合预期,计算仅涉及位运算和算术操作,时间复杂度为O(1)。
内容的提问来源于stack exchange,提问作者montjet
相关产品推荐
相关产品推荐

