我有阵列: [2,4,5,1,4,20]
如何从此数组中获取X最高值?
像这样:
getHighest(2): 25, 5
getHighest(3): 25, 5, 4
答案 0 :(得分:3)
基本思想是创建前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最大,请创建一个最小堆并将比较从<
更改为>
。
答案 1 :(得分:1)
X
元素max
功能查找最大元素。从数组中提取它。重复X
次。答案 2 :(得分:1)
您可以创建一个最小堆,并调用ExtractMin
函数(len(arr) - x)次以获得第X个最大值。
答案 3 :(得分:0)
一个天真的C ++实现是通过快速排序算法对数组进行排序,如下例所示:
void swapArray(int * tab, int ind1, int ind2) {
int swap = tab[ind1];
tab[ind1] = tab[ind2];
tab[ind2] = swap;
}
int sortArray(int * tab, int min, int max) {
int pivot = max;
bool leftSwapping = true;
while(min < max) {
if(leftSwapping) {
if(tab[min] < tab[pivot]) {
swapArray(tab, min, pivot);
pivot = min;
max--;
leftSwapping = false;
} else {
min++;
}
} else {
if(tab[max] > tab[pivot]) {
swapArray(tab, max, pivot);
pivot = max;
min++;
leftSwapping = true;
} else {
max--;
}
}
}
return pivot;
}
void quickSort(int * tab, int min, int max) {
if(min < max) {
int pivot = sortArray(tab, min, max);
quickSort(tab, min, pivot-1);
quickSort(tab, pivot+1, max);
}
};
您可以从数组中循环所需的值。 注意: QuickSort不是一个稳定的算法,因此根据您的原因,合并排序和插入排序在这种情况下很方便。如果你想多次使用getHighest函数,如果不是只使用简单的选择排序并使用你想要的任意数量的值,那就是这种情况。