gpt4 book ai didi

algorithm - 如何从数组中获取 X 个最大值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:33:34 26 4
gpt4 key购买 nike

我有数组:[2, 4, 5, 1, 4, 20]

如何从这个数组中获取 X 个最大值?

像这样:

getHighest(2): 25, 5
getHighest(3): 25, 5, 4

最佳答案

基本思想是创建前 X 项的优先级队列(最大堆)。然后,对于数组中的每个剩余项,如果它小于堆中的第一项,则从堆中删除第一项并添加新项。像这样:

heap = new maxHeap();
for (i = 0; i < X; i++)
{
heap.Add(a[i]);
}
for (; i < a.Length; ++i)
{
if (a[i] < heap.peek())
{
heap.removeFirst();
heap.Add(a[i]);
}
}
// at this point, the smallest X items are on the heap.
// Remove them:
while (!heap.IsEmpty())
{
print(heap.removeFirst());
}

请注意,我上面描述的是如何从数组中获取 X 最小 项。如果你想要 X 最大,创建一个最小堆并将比较从 < 更改为至 > .

关于algorithm - 如何从数组中获取 X 个最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com