2.第k个数

 保证第k小的数永远在区间里面。

 注意:本题是允许有重复数字的。

比如,1 1 2 2 3 3这六个数中,第2小的是1,第5小的是3。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 100010;
 4 int a[N];
 5 int quick_sort(int l, int r, int k) {
 6     if (l == r) {
 7         return a[l];
 8     }
 9     int x = a[(l + r) / 2], i = l - 1, j = r + 1;
10     while (i < j) {
11         while (a[++i] < x);
12         while (a[--j] > x);
13         if (i < j) {
14             swap(a[i], a[j]);
15         }
16     }
17     int sl = j - l + 1;
18     if (k <= sl) {
19         return quick_sort(l, j, k);
20     }
21     return quick_sort(j + 1, r, k - sl); 
22 }
23 int main() {
24     int n, k;
25     cin >> n >> k;
26     for (int i = 0; i < n; i++) {
27         cin >> a[i];
28     }
29     cout << quick_sort(0, n - 1, k) << endl;
30     return 0;
31 }
原文地址:https://www.cnblogs.com/fx1998/p/12803349.html