查找最小的k个元素

1.  题目

    查找最小的k个元素
    题目:输入n个整数,输出其中最小的k个。
    例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。

2. 分析

   初始化最小的k个数,遍历原始数组,将数组的每个元素与k个数中最大的数max做比较,假如比max大则替换

3. 参考代码

#include <iostream>
using namespace std;

// 在pDest中寻找比nData大的对象
// 找到时返回比nData大的序号(即pDest中最大的值的位置),否则返回-1
int FindGreat(int *pDest, int nDestLen, int nData)
{
 if(pDest == NULL)
  return -1;

 int nMaxIndex = 0;
 for(int i=1; i<nDestLen; i++)
 {
  if(pDest[i] > pDest[nMaxIndex])
   nMaxIndex = i;
 }

 if(nData < pDest[nMaxIndex])
  return nMaxIndex;

 return -1;
}

// 在pSrc中寻找最小的nDestLen个数,并将其存入pDest中
bool FindMinNArray(int *pSrc, int nSrcLen, int *pDest, int nDestLen)
{
 if(pSrc == NULL || pDest == NULL)
  return false;

 // 对于最小的几个值负初始值
 for(int i=0; i<nDestLen; i++)
  pDest[i] = pSrc[i];

 int nMaxIndexInDest = -1;
 for(int i=nDestLen; i<nSrcLen; i++)
 {
  nMaxIndexInDest = FindGreat(pDest, nDestLen, pSrc[i]);
  if(nMaxIndexInDest >= 0)
   pDest[nMaxIndexInDest] = pSrc[i];
 }

 return true;
}

 

4. 测试代码

int _tmain(int argc, _TCHAR* argv[])

{
 // 寻找最小的n个数
 int pIntAry[] = {10, -2, 3, 1, -4, 7, 2, 5};
 int pMin[3];
 int nlen = sizeof(pMin)/sizeof(int);
 FindMinNArray(pIntAry, sizeof(pIntAry)/sizeof(int), pMin, nlen);
 for(int i=0; i<nlen; i++)
  cout<<pMin[i] <<" ";

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值