zoukankan      html  css  js  c++  java
  • Introduction to algrithms exercise2.37

    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 部分的算法复杂度。
    未完待续。 


        

  • 相关阅读:
    for 续1
    8 解决多线程对共享数据出错
    7 多线程 全局变量
    6 线程threading
    5 多进程copy文件
    4 进程间通信Queue [kjuː]
    3 进程池
    2 进程multiprocessing [mʌltɪ'prəʊsesɪŋ] time模块
    1 多任务fork Unix/Linux/Mac
    16 pep8 编码规范
  • 原文地址:https://www.cnblogs.com/finallyliuyu/p/1544432.html
Copyright © 2011-2022 走看看