思路
水题,可以直接用 sort 过。另一种思路就是:
因为题中的数据是不重复的,且数据较少,所以直接开一个数组,将对应的位置设置为真,然后从后往前输出即可,也是比较慢的,但也是一种思路。
代码
#include <cstdio>
#include <cstring>
using namespace std;
bool num[1000100];
int main()
{
int n, k, index;
while(scanf("%d%d", &n, &k)==2)
{
memset(num, false, sizeof(num));
for(int i=0; i<n; i++)
{
scanf("%d", &index);
num[index+500000] = true;
}
bool first = true;
int count = 0;
for(int i=1000000; i>=0; i--)
{
if(count==k) break;
if(num[i])
{
if(first) first = false;
else printf(" ");
printf("%d", i-500000);
count++;
}
}
printf("\n");
}
return 0;
}

本文介绍了一种通过排序解决特定问题的方法,并提供了一个C++实现示例。文章中提出两种思路:一是直接使用sort函数;二是利用数组标记数据的存在状态,再逆序输出已标记的数据。这两种方法适用于数据规模较小且不重复的情况。
1556

被折叠的 条评论
为什么被折叠?



