Enderplum @ 2024-06-13 21:48:14
#include<iostream>
#include<random>
#include<cmath>
using namespace std;
int a[5000001], n, k;
int qSearch(int, int, int);
int main(){
srand(time(0));
scanf("%d %d", &n, &k);
for(int i = 0;i < n;i++){
scanf("%d", &a[i]);
}
int q = qSearch(k, 0, n-1);
printf("%d", q);
}
int qSearch(int k, int l, int r){
if(l >= r)
return a[k];
int t = rand() % (r - l + 1) + l;
swap(a[r], a[t]);
int i = l, j = r;
while(i < j){
while(a[i] <= a[r] && i < j){
i++;
}
while(a[j] > a[r] && i < j){
j--;
}
swap(a[i], a[j]);
}
swap(a[i], a[r]);
if(k > i)
return qSearch(k, i+1, r);
else if(k < i) return qSearch(k, l, i-1);
return a[k];
}
by guer_loser_lcz @ 2024-06-13 21:50:41
可以直接用sort
by guer_loser_lcz @ 2024-06-13 21:50:50
@Enderplum
by Enderplum @ 2024-06-13 21:52:29
@lczcy1 sort之前过了,现在想用O(n)的算法做一下