k 数和问题

在之前的几篇文章中Leetcode 1:两数之和(最详细解决方案!!!)Leetcode 167:两数之和 II - 输入有序数组(最详细解决方案!!!)Leetcode 15:三数之和(最详细解决方案!!!)

那么这些问题是不是有一些内在的联系呢?

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 S contains both some number x and its negation −x. The algorithm runs in O ( n k / 2 l o g n ) O(n^{k/2}logn) O(nk/2logn)time.
  • For odd k: Compute the sorted list S of all sums of (k−1)/2 input elements. For each input element aa, check whether S contains both x and a−x, for some number x. (The second step is essentially the O ( n 2 ) O(n^2) O(n2)-time algorithm for 3SUM.) The algorithm runs in O ( n ( k + 1 ) / 2 ) O(n^{(k+1)/2}) 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.

k-SUM问题可以通过如下途径解决:

  • k是偶数:我们首先对输入列表S排序,然后计算输入列表S中的所有k/2的和(例如:对于4-SUM问题,我们计算所有两个数的和),将结果放到一个查找表当中,检查这个查找表中,是不是存在xtarget - x这样的数对,那么这两个数对对应的求和之前的数就是我们要找的结果。这个算法的时间复杂度是 O ( n k / 2 l o g n ) O(n^{k/2}logn) O(nk/2logn)
  • k是奇数:我们首先对输入列表S排序,然后计算输入列表S的所有k-1/2的和,将结果放到一个查找表当中。对每个输入的元素a,检查查找表中是否包含xtarget - a - x这样的数对。这个算法的时间复杂度是 O ( n ( k + 1 ) / 2 l o g n ) O(n^{(k+1)/2}logn) O(n(k+1)/2logn)

另外这里有一篇论文提供了一种新的解法A new algorithm for solving the rSUM problem

你可能感兴趣的:(Data,Structures,and,Algorithms,k数和)