|
In computational complexity theory, the 3SUM problem asks if a given set of real numbers contains three elements that sum to zero. A generalized version, rSUM, asks the same question of ''r'' numbers. 3SUM can be easily solved in time, and matching lower bounds are known in some specialized models of computation . It was widely conjectured that any deterministic algorithm for the 3SUM requires time. In 2014, the original 3SUM conjecture was refuted by Allan Grønlund and Seth Pettie who gave a deterministic algorithm that solves 3SUM in time . It is still conjectured that 3SUM is unsolvable in expected time.〔 When the elements are integers in the range , 3SUM can be solved in time by representing the input set as a bit vector, computing the set of all pairwise sums as a discrete convolution using the Fast Fourier transform, and finally comparing this set to . ==Quadratic algorithm== Suppose the input array is . 3SUM can be solved in time on average by inserting each number into a hash table, and then for each index and , checking whether the hash table contains the integer . Alternatively, the algorithm below first sorts the input array and then tests all possible pairs in a careful order that avoids the need to binary search for the pairs in the sorted list, achieving worst-case time, as follows.〔(Visibility Graphs and 3-Sum ) by Michael Hoffmann〕 sort(S); for i=0 to n-3 do a = S(); start = i+1; end = n-1; while (start < end) do b = S(); c = S(); if (a+b+c == 0) then output a, b, c; // Continue search for all triplet combinations summing to zero. start = start + 1 end = end - 1 else if (a+b+c > 0) then end = end - 1; else start = start + 1; end end end The following example shows this algorithm's execution on a small sorted array. Current values of a are shown in green, values of b and c are shown in red. -25 -10 -7 -3 2 4 8 10 (a+b+c==-25) -25 -10 -7 -3 2 4 8 10 (a+b+c==-22) . . . -25 -10 -7 -3 2 4 8 10 (a+b+c==-7) -25 -10 -7 -3 2 4 8 10 (a+b+c==-7) -25 -10 -7 -3 2 4 8 10 (a+b+c==-3) -25 -10 -7 -3 2 4 8 10 (a+b+c==2) -25 -10 -7 -3 2 4 8 10 (a+b+c==0) The correctness of the algorithm can be seen as follows. Suppose we have a solution a + b + c = 0. Since the pointers only move in one direction, we can run the algorithm until the leftmost pointer points to a. Run the algorithm until either one of the remaining pointers points to b or c, whichever occurs first. Then the algorithm will run until the last pointer points to the remaining term, giving the affirmative solution. 抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「3SUM」の詳細全文を読む スポンサード リンク
|