版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/83023017
在之前的几篇文章中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 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 -time algorithm for 3SUM.) The algorithm runs in 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
问题,我们计算所有两个数的和),将结果放到一个查找表当中,检查这个查找表中,是不是存在x和target - x这样的数对,那么这两个数对对应的求和之前的数就是我们要找的结果。这个算法的时间复杂度是 。k是奇数
:我们首先对输入列表S排序,然后计算输入列表S的所有k-1/2的和,将结果放到一个查找表当中。对每个输入的元素a,检查查找表中是否包含x和target - a - x这样的数对。这个算法的时间复杂度是 。
另外这里有一篇论文提供了一种新的解法A new algorithm for solving the rSUM problem