Introduction to Algorithms 3rd Edition
2.3-7
Describe a nlgn-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.
思想:將x與S各個整數相減等到新數組A,接下來的任務就是搜索S和A中是否有相同元素
解1 nlgn-時間複雜度:
(步驟1)對S排序,採用歸併排序(nlgn)或二分法插入排序(nlgn);
(步驟2)採用二分法搜索(lgn)S,判斷A的n個元素是否在S中存在。
解2 n-時間複雜度:
利用哈希表:
(步驟1)A和S中元素作爲鍵值,對元素遍歷,建立哈希表,遍歷時,對每個鍵值對應存儲空間加1;
(步驟2)遍歷哈希表,如果存在大於1的哈希映射值,則結果爲真,反之亦然。