Description
给你n个整数,请按从大到小的顺序输出其中前m大的数。
Input
每组测试数据有两行,第一行有两个数n,m(0 < n,m < 1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。
Output
对每组测试数据按从大到小的顺序输出前m大的数。
Sample Input
5 3
3 -35 92 213 -644
Sample Output
213 92 3
emm
一开始呢,用快速排序找前m大的数
一提交,超时……淦
后来度娘一搜
原来有计数排序,用空间换时间
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
int num[1000001];
int main()
{
int n, m, i, j, temp;
while (~scanf("%d%d", &n, &m))
{
memset(num, 0, sizeof(num));
for (i = 0; i < n; i++)
{
scanf("%d", &temp);
num[temp + 500000]++;
}
j = sizeof(num) / sizeof(int) - 1;
for (i = 0; i < m; i++)
{
if (i > 0)
printf(" ");
while (num[j] == 0)
j--;
printf("%d", j - 500000);
num[j]--;
}
printf("
");
}
return 0;
}
#include <stdio.h>
#include <memory.h>
unsigned char num[1000001];
int main()
{
int n, m, i, j = 1000000, t;
while (~scanf("%d%d", &n, &m))
{
memset(num, 0, sizeof(num));
while (n--)
{
scanf("%d", &t);
num[t + 500000]++;
}
while (m--)
{
while (num[j] == 0)
j--;
printf("%d%c", j - 500000, m == 0 ? '
' : ' ');
num[j]--;
}
}
return 0;
}
这是快速排序的代码(hdu oj G++过了,sdtbu oj C++超时的):
#include <cstdio>
#include <cstdlib>
int num[1000000];
void quictSort(int, int, int);
int partition(int, int);
int main()
{
int n, m, i;
while (~scanf("%d%d", &n, &m))
{
for (i = 0; i < n; i++)
scanf("%d", &num[i]);
quictSort(0, n - 1, m - 1);
/*
for (i = 0; i < n; i++)
printf("%d ", num[i]);
printf("
", num[i]);
printf("*******
");
*/
for (i = 0; i < m - 1; i++)
printf("%d ", num[i]);
printf("%d
", num[i]);
}
return 0;
}
// 利用快速排序找前m大的数
void quictSort(int left, int right, int mTop)
{
if (left < right)
{
int p = partition(left, right); // 分两段
int len = p - left;
quictSort(left, p - 1, mTop); // 左半段排序
if (len < mTop)
quictSort(p + 1, right, mTop - len); // 右半段排序
}
}
// 从大到小排序
int partition(int left, int right)
{
int key = num[left]; // 第一个元素为基准元素
while (left < right)
{
while (left < right && num[right] <= key) // 从右往左找到比基准元素大的
right--;
if (left < right)
num[left] = num[right]; // 把大的交换到左边
while (left < right && num[left] >= key) // 从左往右找到比基准元素小的
left++;
if (left < right)
num[right] = num[left]; // 把小的交换到右边
}
num[left] = key; // 把基准元素赋值回去
return left;
}