我如何在数组中组装一组最小或最大的数字?例如,如果我想在大小为1000的数组中找到最小的10个数字。
我正在使用C语言,但我不需要特定于语言的答案。我只是试图找出处理这种任务的方法,因为最近经常遇到这种情况。
O(n)
,而QuickSelect
在最坏情况下的时间复杂度为O(n^2)
,我建议使用排序算法。 - EOFO(nlogk)
复杂度的二进制堆)。请注意,在一般情况下,Q/S 通常是首选排序算法。 - MBo您可以对数组执行类似快速排序的操作,并获取前10个元素。但这样做效率相对较低,因为您只关心前10个元素,而对整个数组进行排序是过度的。
int lowerTen = malloc(size_of_array);
//'array' is your array with 1000 elements
for(int i=0; i<size_of_array; i++){
if(comesUnderLowerTen(array[i], lowerTeb)){
addTolowerTen(array[i], lowerTen)
}
}
int comesUnderLowerTen(int num, int *lowerTen){
//if there are not yet 10 elements in lowerTen, insert.
//else if 'num' is less than the largest element in lowerTen, insert.
}
void addToLowerTen(int num, int *lowerTen){
//should make sure that num is inserted at the right place in the array
//i.e, after inserting 'num' *lowerTen should remain sorted
}
int lowerTen = (int*)malloc(size_of_array);
。1)在C语言中,对返回值进行强制类型转换只会让代码变得混乱。返回类型是 void*
,可以赋值给任何其他指针类型。2)malloc()
返回一个指针,而 int lowerTen
是一个整数,不是一个指针。 - user3629249for(int i=0; i<array.length; i++){
。在 C 语言中,数组没有 .length
属性。 - user3629249实现一个优先队列。 循环遍历所有数字并将它们添加到该队列中。 如果该队列的长度等于10,则开始检查当前数字是否小于该队列中最高的数字。 如果是,则删除该最高数字并添加当前数字。
最终,您将拥有一个包含数组中10个最低数字的优先队列。 所需时间应为O(n),其中n是数组的长度。
如果需要更多提示,请添加评论 :)
以下是代码:
现在,附上代码:
#include <stdlib.h> // size_t
void selectLowest( int *sourceArray, size_t numItemsInSource, int *lowestDest, size_t numItemsInDest )
{
size_t maxIndex = 0;
int maxValue = 0;
// initially populate lowestDest array
for( size_t i=0; i<numItemsInDest; i++ )
{
lowestDest[i] = sourceArray[i];
if( maxValue < sourceArray[i] )
{
maxValue = sourceArray[i];
maxIndex = i;
}
}
// search rest of sourceArray and
// if lower than max in lowestDest,
// then
// replace
// find new max value
for( size_t i=numItemsInDest; i<numItemsInSource; i++ )
{
if( maxValue > sourceArray[i] )
{
lowestDest[maxIndex] = sourceArray[i];
maxIndex = 0;
maxValue = 0;
for( size_t j=0; j<numItemsInDest; j++ )
{
if( maxValue < lowestDest[j] )
{
maxValue = lowestDest[j];
maxIndex = j;
}
}
}
}
} // end function: selectLowest