- 空间限制:32768K
- 算法知识视频讲解
题目描述
输入n个整数,输出其中最小的k个。
详细描述:
接口说明
原型:
bool GetMinK(unsignedint uiInputNum, int * pInputArray, unsignedint uiK, int * pOutputArray);
输入参数:
unsignedint uiInputNum //输入整数个数
int * pInputArray //输入整数数组
unsignedint uiK //需输出uiK个整数
输出参数(指针指向的内存区域保证有效):
int * pOutputArray //最小的uiK个整数
返回值:
false 异常失败
true 输出成功
输入描述:
输入说明 1 输入两个整数 2 输入一个整数数组
输出描述:
输出一个整数数组
输入例子:
5 2 1 3 5 7 2
输出例子:
1 2
#include<iostream> #include<stdlib.h> #include<algorithm>
using namespace std; bool GetMinK(unsigned int uiInputNum, int *pInputArray, unsigned int uiK, int *pOutputArray) { unsigned int innum = uiInputNum; unsigned int outnum = uiK; unsigned int i = 0; int *p1 = pInputArray; int *p2 = pOutputArray; if (innum == 0 || p1 == NULL || outnum == 0 || p2 == NULL) return false;
sort(p1, p1 + innum);
for (i = 0; i<outnum; i++) { p2[i] = p1[i]; }
for (i = 0; i<outnum-1; i++) cout << p2[i] << " "; cout << p2[i]; //cout << endl; //多了此行通不过 return true; } int main() { unsigned int n, k, i; int inarray[2000] = { 0 }, outarray[2000] = { 0 };
while (cin >> n >> k) { for (i = 0; i<n; i++) cin >> inarray[i];
GetMinK(n, inarray, k, outarray);
}
return 0; }
#include<iostream> #include<stdlib.h> #include<algorithm> using namespace std; bool GetMinK(unsigned int uiInputNum, int *pInputArray, unsigned int uiK, int *pOutputArray) { unsigned int innum = uiInputNum; unsigned int outnum = uiK; unsigned int i = 0; int *p1 = pInputArray; int *p2 = pOutputArray; if (innum == 0 || p1 == NULL || outnum == 0 || p2 == NULL) return false; sort(p1, p1 + innum); for (i = 0; i<outnum; i++) { p2[i] = p1[i]; } for (i = 0; i<outnum-1; i++) cout << p2[i] << " "; cout << p2[i]; //cout << endl; //多了此行通不过 return true; } int main() { unsigned int n, k, i; int inarray[2000] = { 0 }, outarray[2000] = { 0 }; while (cin >> n >> k) { for (i = 0; i<n; i++) cin >> inarray[i]; GetMinK(n, inarray, k, outarray); } return 0; }
#include<iostream> #include<stdlib.h> #include<algorithm> using namespace std; bool GetMinK(unsigned int uiInputNum, int *pInputArray, unsigned int uiK, int *pOutputArray) { unsigned int innum = uiInputNum; unsigned int outnum = uiK; unsigned int i = 0; int *p1 = pInputArray; int *p2 = pOutputArray; if (innum == 0 || p1 == NULL || outnum == 0 || p2 == NULL) return false; sort(p1, p1 + innum); for (i = 0; i<outnum; i++) { p2[i] = p1[i]; } for (i = 0; i<outnum-1; i++) cout << p2[i] << " "; cout << p2[i]; //cout << endl; //多了此行通不过 return true; } int main() { unsigned int n, k, i; int inarray[2000] = { 0 }, outarray[2000] = { 0 }; while (cin >> n >> k) { for (i = 0; i<n; i++) cin >> inarray[i]; GetMinK(n, inarray, k, outarray); } return 0; }