xffdeg @ 2024-08-27 20:04:49
#include <iostream>
using namespace std;
int ans = 0 , k;
void findkth(int a[] , int l , int r){
if(l == r){
ans = a[l];
return;
}
int i = l , j = r , flag = a[(l + r) / 2] , tmp;
do{
while(a[i] < flag) i++;
while(a[j] > flag) j--;
if(i <= j){
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
}while(i <= j);
if(k <= j)findkth(a, l, j);
else if(k <= i)findkth(a, i, r);
else findkth(a , j + 1 , i - 1);
}
int main (){
int n;
cin >> n >> k;
int a[n];
for(int i = 0;i < n;i++)
cin >> a[i];
findkth(a, 0, n - 1);
cout << ans << endl;
return 0;
}
如果能优化的话送关注
by chenhaihang @ 2024-08-27 20:13:33
#include<bits/stdc++.h>
using namespace std;
int n,m,a[5000001];
int main()
{
std::ios::sync_with_stdio(false);//写了就只能用cincout但会更快
cin>>n>>m;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a+0,a+n);快速排序
cout<<a[m];
return 0;
}
@xffdeg
by xffdeg @ 2024-08-27 20:13:33
@dream_dad 能具体列一下吗
by Yxy7952 @ 2024-08-27 20:13:51
@xffdeg
如果只是单纯为了AC,代码如下,侥幸能过
#include<bits/stdc++.h>
using namespace std;
int n,k,a[5000005];
int main(){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
sort(a+1,a+n+1);
printf("%d",a[k+1]);
return 0;
}
by xffdeg @ 2024-08-27 20:14:47
@chenhaihang 以关注谢谢指导
by Yxy7952 @ 2024-08-27 20:14:48
@xffdeg
但是这道题的初衷设计不是这样的,楼主可以看一下题解
by xffdeg @ 2024-08-27 20:15:20
@yixingyou 以关注谢谢指导