Describe a (nlgn)-time algorithm that, given a set S of integers and another integer x, determings whether or not there exist two elements in S whose sum is exactly x.
汉语:描述一个nlgn复杂度的算法:给定一个n个数字的集合,和另一个数字x,判断集合中是否存在两个数字,它们的和是x
题目分析及伪代码实现
        
如果算法复杂度为n^2,那么很好设计比如可以采用以下算法
TestExistence(A,begin,end,x)
 for i<-1 to n  
      for j<-i+1 to n
             if a[i]+a[j]=x
              then return i,j
return 0,0
现在要求算法复杂度为nlgn.通过本章的学习,我们知道折半查找和归并法爬序的算法复杂度为nlgn。所以我们猜想这个题目的算法可能和这两种算法挂上钩。
伪代码实现
TestExsistence(S,begin,end,x)
1. MergeSort(S,begin,end);
2.Create S' 
for i<-1 to n
S'[i]=x-S[i];
3.MergeSort(S',begin,end);
4.purge S,S' seperately;
 4.1 TestEqual(x,y);//比较两个元素是否相等
5. if the merged output contains two consecutive equal value ,the answer is true.
控制此算法复杂度数量级的关键在于控制purge 部分的算法复杂度。
未完待续。 


    

posted on 2009-08-12 14:27  finallyly  阅读(214)  评论(1编辑  收藏  举报