Quadratic algorithm for 4-SUM

后端 未结 3 506
庸人自扰
庸人自扰 2020-12-03 08:55

The 4-SUM is as follows:

Given an array of N distinct integers find 4 integers a, b, c, d such that a+b+c+d = 0.

I could come up

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 09:13

    There is also a O(N2) algorithm for this problem using O(N2) extra memory.

    1. Generate all the pairwise sums in O(N2) and store the pair (ai, aj) in a hash table and use the absolute value of their sum as the key of the hash table (ai and aj are two distinct numbers of the input array)

    2. Iterate over the table and find a key which has both negative and positive sum with four distinctive elements and return is as the answer

    There is an alternative if you prefer not using hash table. Since your numbers are integers, you can sort the list of all the sum in a linear time of the elements in the sum list using something like a Radix sort (there are O(N2) elements in the sum list).

提交回复
热议问题