xk2013 @ 2024-03-24 13:36:03
#include <cstdio>
#include <cstdlib>
#include <ctime>
int ans, n, k, *a;
void findkth(int l, int r);
int main(void)
{
srand(time(NULL));
scanf("%d%d", &n, &k);
a = new int[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
findkth(0, n - 1);
printf("%d", ans);
}
void findkth(int l, int r)
{
if (l == r)
{
ans = a[l];
return;
}
int i = l, j = r, flag = a[rand() % (r - l) + l];
do
{
while (a[i] < flag)
{
i++;
}
while (a[j] > flag)
{
j--;
}
if (i <= j)
{
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
i++;
j--;
}
}
while (i <= j);
if (k <= j)
{
findkth(l, j);
}
else if (i <= k)
{
findkth(i, r);
}
else
{
findkth(j + 1, i - 1);
}
}
by xk2013 @ 2024-03-24 13:36:32
@chat_jinxuan @xsy2013 @wei2013
by wei2013 @ 2024-03-24 13:49:02
#include <bits/stdc++.h>
using namespace std;
int a[5000005];
int main(){
int n,k;
cin>>n>>k;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
nth_element(a,a+k,a+n);
cout<<a[k];
return 0;
}
@xk2013
by xk2013 @ 2024-03-24 13:51:59
@wei2013 我不要 nth_element!