思路:
类似于快排的分治算法。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 7 const int MAXN = 1000000; 8 int a[MAXN + 5], n, k; 9 10 int partition(int * num, int l, int r) 11 { 12 int i = l, j = r, m = (l + r) >> 1; 13 int x = num[m]; 14 while (i != j) 15 { 16 while (j > m && num[j] >= x) 17 { 18 j--; 19 } 20 num[m] = num[j], m = j; 21 while (i < m && num[i] <= x) 22 { 23 i++; 24 } 25 num[m] = num[i], m = i; 26 } 27 num[i] = x; 28 return i; 29 } 30 31 int findK(int * num, int l, int r, int k) 32 { 33 int pos = partition(num, l, r); 34 if (pos == k) 35 { 36 return num[k]; 37 } 38 if (pos > k) 39 { 40 return findK(num, l, pos - 1, k); 41 } 42 return findK(num, pos + 1, r, k); 43 } 44 45 int main() 46 { 47 scanf("%d %d", &n, &k); 48 for (int i = 1; i <= n; i++) 49 { 50 scanf("%d", &a[i]); 51 } 52 printf("%d\n", findK(a, 1, n, k)); 53 return 0; 54 }
时间: 2024-11-05 12:35:08