algorithm - 如何设计时间复杂度为 O(n log n) 的搜索算法?

标签 algorithm time logarithm

Describe a O(n log n)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.

我计划为此使用二进制搜索。

ALGORITHM(S,x)
S=Insertion-Sort()
for i=1 to S.length
   n=x-S[i]
   if( Binary-Search(S,n) == true)
      return { S[i],n }


Binary-Search(A, v)
low=1
high=A.length

while low ≤ high
   mid=(low+high)/2

   if v = A[mid]
     return mid
   if v > A[mid]  
      low ← mid+1
   else
      high ← mid−1
 return NIL 

我如何找到这个算法的时间复杂度?如果 T(n) 不是 (n log n),那么正确的算法是什么?

最佳答案

算法的整体顺序由各个部分的最高顺序决定。您从插入排序开始,其 worst-case performance is O(n^2)所以你已经失败了。

如果您要用 O(n log n) 版本替换排序算法,那么您必须查看剩下的内容。您有一个长度为 n 的循环,循环体调用二分查找。正确编码的二进制搜索是 O(log n),因此结果应该是 O(n log n)。添加两个 O(n log n) 进程仍然会留下 O(n log n)。

执行第二步还有另一种更快的方法,但我会将其留给您去发现。它不会影响整体结果。

关于algorithm - 如何设计时间复杂度为 O(n log n) 的搜索算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18471133/

相关文章:

django - 为什么 Postgres 查询比 Redis 查询快?

java - 性能指标: Java vs JavaCard

r - R中的标签对数刻度显示

python - 用 Python 计算对数

python - 将与特定对象属性相对应的所有值相加的可靠方法?

algorithm - 什么是用于表示解剖拼图 block 的智能数据结构?

java - 用扭曲遍历一个无向、未加权的图 : minimum visits to each node

c# - Unity WaitForSeconds 不工作 c#

algorithm - 点的对数绘图

algorithm - agda 中类似 "!=<"的错误意味着什么以及如何修复