Description
找出长度为N的数组A中的第K大数字。(N>=K)
Input Format
第一行为两个整数
N和K。第二行为数组A。
Output Format
一个数字。
Sample Input
5 2
7 1 5 9 8
Sample Output
8
Tips
复杂度应控制在 O(N log K) 或者 O(N + K log N)
#include <iostream>
using namespace std;
void mymergeSort(int* a, int left, int mid, int right)
{
int* tmp = new int[right - left + 1];
int i = left, j = mid, k = 0;
while (i < mid && j <= right)
if (a[i] < a[j]) tmp[k++] = a[i++];
else tmp[k++] = a[j++];
while (i < mid) tmp[k++] = a[i++];
while (j <= right) tmp[k++] = a[j++];
for (i = 0, k = left; k <= right;) a[k++] = tmp[i++];
delete[]tmp;
}
void mergeSort(int* a, int left, int right)
{
int mid = (left + right) / 2;
if (left == right) return;
mergeSort(a, left, mid);
mergeSort(a, mid+1, right);
mymergeSort(a, left, mid + 1, right);
}
int main()
{
int N, K;
cin >> N >> K;
int* a = new int[N];
for (int i = 0; i < N; ++i)
cin >> a[i];
mergeSort(a, 0, N - 1);
cout << a[N-K] << endl;
}