时间限制:1S
空间限制:32768K
题目描述:
给定无序整数序列,求第K大的数,例如{45,67,33,21},第2大的数为45
输入描述:
输入第一行为整数序列,数字用空格分割,如:45 67 33 21
输入第二行为一个整数K,K在数组长度范围内,如:2
输出描述:
输出第K大的数,本例为第2大的数:45
示例:
输入
45 67 33 21
2
输出
45
思路:本题数据小直接暴力,求类似的题目可以用快排思想,代码中注释部分为排序求解
#include <iostream>
using namespace std;
const int Maxn = 1005;
void swap(int a[Maxn], int l, int r)
{
int temp = a[l];
a[l] = a[r];
a[r] = temp;
}
int quickSort(int a[Maxn], int k, int l, int r)
{
if(l==r)
return a[l];
int key = a[l];
int left = l, right = r;
while(left<right)
{
while(a[right]<key && left<right)
right--;
if(left<right)
swap(a, left, right);
while(a[left]>=key && left<right)
left++;
if(left<right)
swap(a, left, right);
}
a[left] = key;
if(left==k)
return a[left];
else if(left>k)
return quickSort(a, k, l, left-1);
else
return quickSort(a, k, left+1, r);
}
int main()
{
int a[Maxn], k;
int count = 0;
while(cin >> a[count++]);
cout << quickSort(a, a[count-2]-1, 0, count-3) << endl;
return 0;
}
/*
45 67 33 21
2
*/
//#include <iostream>
//#include <algorithm>
//using namespace std;
//const int Maxn = 1005;
//
//int cmp(const int& a, const int& b)
//{
// return a>b;
//}
//
//int main()
//{
// int a[Maxn], k;
// int count = 0;
// while(cin >> a[count++]);
// sort(a, a+count-2, cmp);
// cout << a[a[count-2]-1] << endl;
// return 0;
//}