TLE,求助

P1923 【深基9.例4】求第 k 小的数

bacfdml @ 2024-12-22 22:47:41

#include <bits/stdc++.h>
using namespace std;
int main()
{
 int a[5000000],n,k,x;
 cin>>n>>k;
 for(int i=0;i<n;i++){
  cin>>a[i];
 }
 for(int i=0;i<n;i++){
  for(int j=i+1;j<n;j++){
   if(a[i]>a[j]){
    x=a[i];
    a[i]=a[j];
    a[j]=x;
   }
  }
 }
 cout<<a[k-1];
 return 0;
}

by Terrible @ 2024-12-22 22:54:18

查看题解


by MaCity @ 2024-12-23 07:40:01

@bacfdml

用nth_element即可


by cat_Cat_small @ 2024-12-28 21:57:46

#include<bits/stdc++.h>
using namespace std;
int x[5000005],k;
int main()
{
    int n;
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++)
        scanf("%d",&x[i]);
    sort(x,x+n);
    printf("%d",x[k]);
}

by cat_Cat_small @ 2024-12-28 22:01:10

@bacfdml 请使用快排!!


|