[英]Algorithm to find three elements which sum to zero in O(n log n) time complexity
假設 n 個整數的輸入數組僅包含 -5000n 到 6000n 之間的整數。 我們需要找到一種算法,在 O(n log n) 時間內確定數組是否包含三個總和為零的元素。
我的方法:
1. Sort in O(n log n) time.
2. Run a loop in O(n) time
3. Fix two left and right pointers in the sorted array as the two endpoints
4. find = SUM - (A[left] + A[right])
5. Search for the third element (find) using binary search in O(log n)
6. if found then return TRUE
7. else
8.
我卡在第 8 步,如果二分查找算法返回 false 那么應該如何調整左右指針?
此外,由於我沒有評估所有可能的組合,整個算法是否會在每種情況下都找到總和為零的三個元素?
您不在通往 O(N log N) 算法的道路上。 您的算法要么是 O(N 2 ) 要么被破壞,這取決於您如何完成它。
該問題旨在使用 FFT 卷積來解決,如下所示:
分配一個大小為 W 的數組,其中 W 是 2 的冪並且大於 22001N。
用零填充數組,然后為輸入數組中的每個值 v 設置 array[v+5000N]=1。
將數組與其自身進行卷積:計算 FFT,對每個結果值進行平方,然后計算 IFFT。
對於輸入中的每個值 v,檢查 ifft[10000N-v] 是否 > 0。如果是,則輸入中有兩個數字加起來等於 -v。 對輸入數組進行排序並使用傳統的兩指針搜索來查找其他兩個數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.