Find the kth largest element in an unsorted array A
阿新 • • 發佈:2018-11-23
Problem description
Find the kth largest element in an unsorted array A . Note that it is the kth largest element in the sorted order, not the kth distinct element. The range of length of A is N(1≤N≤5,000,000) and the element (integer) in A is no bigger than 10,000,00000.
Input
Line 1: the length of the unsorted array A and the index k. Line 2: the all elements in array A and split by spaces
Output
Line 1: A single integer that is the kth largest element in an unsorted array A.
Sample Input 1
8 2
1 3 5 7 4 2 6 8
Sample Output 1
7
Sample Input 2
8 2
1 1 2 2 3 3 4 4
Sample Output 2
4
#include<stdio.h> #include<algorithm> using namespace std; int main() { int a[5000000]; int len, temp, i, k, j; scanf("%d", &len); scanf("%d", &k); for (i = 0; i<len; i++) { scanf("%d", &a[i]); } sort(a, a + len); printf("%d\n", a[len-k]); return 0; }