救救孩子吧,2WA,2RE,1TLE
查看原帖
救救孩子吧,2WA,2RE,1TLE
693498
207394848R楼主2022/3/19 16:55
#include<cstdio>
#include<cctype>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<climits>
#include<map>
using namespace std;

const int maxn = 5000000;
int randPartition(int A[], int left, int right)
{
	int p = (round(1.0 * rand() / RAND_MAX * (right - left) + left));
	swap(A[p],A[left]);
	int temp = A[left];
	while (left < right)
	{
		while (left<right && A[right]>temp)
		{
			right--;
		}
		A[left] = A[right];
		while (left < right && A[left] <= temp)
		{
			left++;
		}
		A[right] = A[left];
	}
	A[left] = temp;
	return left;
}
void quickSort(int A[],int left,int right)
{
	if (left<right)
	{
		int pos = randPartition(A, left, right);
		quickSort(A, left, pos - 1);
		quickSort(A, pos + 1, right);
	}
	
}

int randSelect(int A[],int left,int right,int K)
{
	if (left==right)
	{
		return A[left];
	}
	int p = randPartition(A, left, right);
	int M = p - left + 1;
	//int M = p - left;
	if (K==M)
	{
		return A[p];
	}
	else if (K<M)
	{
		return randSelect(A, left, p - 1, K);
	}
	else
	{
		return randSelect(A, p + 1, right, K - M);
	}
 }

int nums[maxn];

int main() {
	int n,k;
	scanf("%d%d", &n, &k);
	for (int i = 0; i < n; i++)
	{
		int val;
		cin >> val;
		nums[i] = val;
	}
	int pos = randSelect(nums, 0, n - 1, k+1);
	printf("%d", nums[pos-1]);
	return 0;
}
2022/3/19 16:55
加载中...