arrays - 总和至少为 K 的最小数字集

标签 arrays algorithm sorting

给定一个包含 n 个对象的列表,编写一个函数输出总和至少为 K 的最小数字集。跟进:你能打败 O(n ln n) 吗?

最小集合将是一个包含 1 个元素的集合。难道我们只需要遍历数组并找到一个元素,即 >= K。

否则对于 O(nlgn),我知道我们必须首先对数组进行排序,然后我们才能找到总和 >=k 的对或三元组。 如果我们找不到这样的组合而不得不寻找更大的集合,这个问题会不会与 N 和问题相同?

最佳答案

这是一个使用线性时间中值查找作为子程序的线性算法:

Findsum(A, K) {
  Let n be the length of A.
  Let M be the median element of A, found in linear time.
  Let L be the elements of A less than M.
  Let U be the elements of A greater than M.
  Let E be the elements of A equal to M.
  If the sum of the elements in U is at least K,
    Return Findsum(U, K).
  Else, if the sum of the elements in U and E is at least K,
    Return U together with enough elements of E that the sum is at least K.
  Else,
    Return Findsum(L, K - sum(U) - sum(E)).
}

每个递归调用都在一个列表上完成,该列表的大小最多为 A 的一半,并且所有其他步骤最多花费线性时间,因此该算法总体上花费线性时间。

关于arrays - 总和至少为 K 的最小数字集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14431529/

相关文章:

java - 如何按空格分割字符串

c - 如何在 C 中用连分数实现自然对数​​?

c# - 在时间轴恒定的位置和速度给定点的情况下构造曲线桥图的算法

c# - 通过反射按自定义属性对实体进行 Linq 排序

javascript - 如果包含键值对,则返回数组中的对象

iphone - NSMutableArray removeObjectAtIndex : Behaviour

c - 在 malloc() 之后使用 realloc() 来改变 unsigned char 数组的大小

algorithm - 具有最小值、最早值和键频率的数据结构

python - 如何对二维列表进行排序?

java - 比较方法违反了它的一般契约!在java中对图像轮廓进行排序时