[剑指offer][面试题30]最小的k个数
2013-10-17 14:52
405 查看
输入n个整数,输出其中最小的K个数。例如,输入1、2、3、4、5、6、7、8这8个数字,则最小的4个数字为1、2、3、4。
#include <iostream> using namespace std; void swap(int& a, int& b) { int t = a; a = b; b = t; } int partition(int *piIn, int iLen, int iStart, int iEnd) { if (iStart>=iEnd){ return iStart; } int iSmall = iStart-1; int iBig = iStart; while (iBig<iEnd){ if (piIn[iBig]<piIn[iEnd]){ iSmall++; swap(piIn[iSmall], piIn[iBig]); } iBig++; } iSmall++; swap(piIn[iSmall], piIn[iEnd]); return iSmall; } bool findLeastKNums(int *piIn, int iLenIn, int *piOut, int iK) { if (!piIn || !piOut || iLenIn<=0 || iK<=0 || iK>iLenIn){ return false; } int iStart = 0; int iEnd = iLenIn-1; int iIndex = partition(piIn, iLenIn, 0, iLenIn-1); while ( iIndex!=(iK-1) ){ if (iIndex>iK-1){ iEnd = iIndex-1; iIndex = partition(piIn, iLenIn, 0, iEnd); } else{ iStart = iIndex+1; iIndex = partition(piIn, iLenIn, iStart, iLenIn-1); } } memcpy(piOut, piIn, iK*sizeof(int)); return true; } int main() { int data[8] = {4,5,1,6,2,7,3,8}; int out[8] = {0}; cout<<"\n Input:"; for (int i=0; i<8; i++){ cout<<data[i]<<" "; } for (int iK=1; iK<9; iK++){ findLeastKNums(data, 8, out, iK); cout<<"\n iK="<<iK<<", Output:"; for (int i=0; i<iK; i++){ cout<<out[i]<<" "; } } }
相关文章推荐
- 剑指offer——面试题30:最小的K个数
- 剑指Offer面试题30(java版):最小的k个数
- 剑指Offer面试题30最小的K个数(涉及堆或快排)
- 剑指offer——面试题30:最小的k个数
- 剑指offer面试题30:最小的K个数
- 剑指offer 面试题30—最小的k个数
- 剑指offer - 面试题30 找出数组最小的k个数
- 剑指offer - 面试题30 找出数组最小的k个数
- 【剑指offer】面试题30:最小的 K 个数
- 剑指offer-面试题30-最小的K个数
- 剑指offer 面试题30 最小的 k 个数
- 剑指Offer面试题30:最小的k个数 Java不同算法实现
- 【剑指offer】面试题30:最小的K个数
- 【剑指offer】面试题30:最小的K个数
- 剑指Offer面试题30(java版):最小的k个数
- 剑指Offer_面试题30_最小的k个数
- 【面试题】剑指Offer-30-最小的第K个数
- 剑指offer 面试题30:最小的K个数(topK问题) 题解
- 剑指offer 面试题30 找出数组中最小的k个数
- 【剑指Offer】面试题30:最小的k个数