kSum問題的總結


    kSum問題是一類題型,常見的有2Sum,3Sum,4Sum等。這篇博文就來總結一些kSum問題的解法,以及對應的時間複雜度。


    1. 2Sum

    在一個給定的數組nums中,尋找和爲定值target的兩個數。
    【解法1】:把數組排序,然後使用two pointers的方法來求解。時間複雜度分析:排序O(nlogn),兩指針遍歷O(n),總體O(nlogn).
    【解法2】:先遍歷一遍,把整個數組存入到hash_map中,key是每個數,value是出現的次數。然後再遍歷一次,每次取查找hasp_map中是否有target-nums[i]。建立hash_map的時間複雜度是O(n),第二次遍歷時 每個查找爲O(1),所以查找全部也是O(n),總體爲O(n)。注意:如果數組中有重複的數,比如{1, 5, 3, 3}, target=6,那麼我們在查找的時候就要考慮3的情況,正是因爲數組中有兩個3,我們才能返回,此時key=3是的value=2就起到了作用。這就是爲什麼我們前面要記錄value的原因。

    總的來說,2Sum的最好時間複雜度是O(n)。
    
    代碼:http://blog.csdn.net/puqutogether/article/details/41775343

    2. 3Sum

    在一個給定的數組nums中,尋找和爲定值target的三個數。
    【解法1】:固定其中的一個數a,問題便轉換爲尋找2Sum,新的target爲target-a。時間複雜度爲O(nlogn + n^2)=O(n^2)。
    【解法2】:依然是固定其中一個數,之後使用hash_map的做法,時間複雜度還是O(n*n)=O(n^2)。
 
    總體的最好的時間複雜度是O(n^2)。

    3. 4Sum

    一個給定的數組nums中,尋找和爲定值target的三個數。
    【解法1】:使用不斷固定的思想,最後轉化成2Sum問題,時間複雜度爲O(n^3).
    【解法2】:既然前面的hash_map的思路展示出優勢,那麼我們就直接使用hash_map來解決。
                      首先,遍歷所有可能的pair,把所有的pair存在hash_map中,key=a+b, value是一個list,每個元素爲(a, b)。時間複雜度爲O(n^2),爲啥是pair呢?因爲後面要查找的是pair。
                      然後,兩個循環for遍歷所有的可能值c和d,O(n^2),每種情況下都需要查找target-c-d,此時,這個差值就是我們hash_map中的key,如果發現有pair滿足要求即返回。
                      時間複雜度爲O(n^2*logn),因爲list的查找至少要O(logn)。所以,解法2的總體時間複雜度爲O(n^2logn)。

    4. kSum

    關於kSum問題,我們一樣可以使用上述解法1的思路,這樣的時間複雜度爲O(n^(k-1))。也可以使用hash_map的思路,這樣子會更快。具體的時間複雜度分析較複雜,參考如下:

k-SUM can be solved more quickly as follows.

  • For even k: Compute a sorted list S of all sums of k/2 input elements. Check whether Scontains both some number x and its negation x. The algorithm runs in O(nk/2logn) time.

  • For odd k: Compute the sorted list S of all sums of (k1)/2 input elements. For each input element a, check whether S contains both x and ax, for some number x. (The second step is essentially the O(n2)-time algorithm for 3SUM.) The algorithm runs in O(n(k+1)/2) time.

Both algorithms are optimal (except possibly for the log factor when k is even and bigger than 2) for any constant k in a certain weak but natural restriction of the linear decision tree model of computation. For more details, see:


參考鏈接:
http://cs.stackexchange.com/questions/2973/generalised-3sum-k-sum-problem.
http://blog.csdn.net/doc_sgl/article/details/12462151


發佈了258 篇原創文章 · 獲贊 86 · 訪問量 78萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章