最后两个超时

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

HGerdd @ 2024-03-05 17:08:06

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

vector<int> a(50000005);

void quick(vector<int> &a,int low, int high, int k)
{
    if(low <= high)
    {
        int i = low, j = high;
        int x = a[i];
        while(i < j)
        {
            while(i < j && a[j] >= x) j--;
            a[i] = a[j];
            while(i < j && a[i] <= x) i++;
            a[j] = a[i];
        }
        a[i] = x;
        //cout << i << " " << x << endl;
        if(i == k)
        {
            cout << x;
            return;
        }
        else if(k < i)
        {
            quick(a,low, i-1,k);
            return;
        }
        else
        {
            quick(a,i+1, high,k);
            return;
        }

    }
}

int main()
{
    int n,k;
    cin >> n >> k;  
    for(int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    quick(a,0,n-1,k);
    return 0;
}

by dthythxth_Huge_Brain @ 2024-03-05 17:10:32

@HGerdd 建议使用较快的排序方法


by Dannylxy2012 @ 2024-03-06 20:37:37


using namespace std;
int n,a[10005],k;
int main(){
    cin>>n>>k;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a+0,a+n);
    cout<<a[k];
    return 0;
} ```

|