Problem 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解题思路: 刚看到这个题,数据那么大,就觉得用排序方法应该是会超时的,所以就选了快速排序试一试的心 态,最终是没有达到效果,后来网络里搜一下,知道了另一种对数据的处理方法,直接把数据弄到数组里,就 相当于已经排序了,这是一种不普通的解法,还是异于寻常的。速度还是非常的快。我的快速排序的代码如下:
- #include<iostream>
- using namespace std;
- int a[1000001]={0};
- int n,m;
- int Partition(int a[],int low,int high) //进行一趟的排序
- {
- int pre=a[low];
- while(low<high)
- {
- while(low<high&&a[high]>=pre)
- high--;
- int temp;
- temp=a[low];
- a[low]=a[high];
- a[high]=temp;
- while(low<high&&a[low]<=pre)
- low++;
- temp=a[low];
- a[low]=a[high];
- a[high]=temp;
- }
- return low;
- }
- void QSort(int a[],int low,int high) //递归
- {
- if(low<high)
- {
- int pivotloc=Partition(a,low,high);
- QSort(a,low,pivotloc-1);
- QSort(a,pivotloc+1,high);
- }
- }
- void QuickSort(int a[],int j)
- {
- QSort(a,1,j-1);
- }
- int main()
- {
- int temp;
- while(cin>>n>>m)
- {
- int j=1;
- for(int i=1;i<=n;i++)
- {
- cin>>temp;
- if(temp>=m)
- {
- a[j]=temp;
- j++;
- }
- }
- QuickSort(a,j);
- for(i=j-1;i>0;i--)
- cout<<a[i]<<endl;
- }
- return 0;
- }
推荐AC的方法(代码如下):
- #include <stdio.h>
- int main()
- {
- unsigned n, m;
- int x;
- char a[1000001] = {0};
- while (scanf("%d%d", &n, &m) != EOF)
- {
- while (n--)
- {
- scanf("%d", &x);
- a[500000+x]++;
- }
- for (x = 1000000; m; x--)
- {
- if (a[x])
- {
- printf("%d", x-500000);
- if (--m)
- putchar(32);
- else
- putchar(10);
- a[x]--;
- }
- }
- }
- return 0;
- }