求第k小的数 - 题解
求第k小的数
时间限制:C/C++ 1500MS,其他语言 3000MS
内存限制:C/C++ 256MB,其他语言 512MB描述
输入 \(n\) 个数字,输出这些数字的第 \(k\) 小的数。最小的数是第 \(0\) 小。
输入描述
第一行包含两个整数 \(n(1≤n≤5000000)\) 和 \(k(0≤k<n)\)。
输出描述
1 个整数(所有整数均在 \(1∼10^9\) 范围内)。
用例输入 1
5 1 4 3 2 1 5 用例输出 1
2 提示
请不要
nth_element()
函数。
代码
#include<cstdio> #include<algorithm> using namespace std; inline int read() { int x=0,w=1;char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-') x=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { x=(x<<3)+(x<<1)+(ch^'0'); ch=getchar(); } return x*w; } const int N=5e6+5; int n,k,a[N]; int QuickSort_FindNth(int l,int r,int nth) { if(l>=r) return a[l]; int i=l-1,j=r+1, p=a[(l+r)>>1]; while(i<j) { do i++; while(a[i]<p); do j--; while(a[j]>p); if(i<j) swap(a[i],a[j]); } if(nth<=j) return QuickSort_FindNth(l,j,nth); else return QuickSort_FindNth(j+1,r,nth); } int main() { n=read(),k=read(); for(int i=1;i<=n;i++) a[i]=read(); printf("%d\n",QuickSort_FindNth(1,n,k+1)); return 0; }
本文采用 「CC-BY-NC 4.0」 创作共享协议,转载请注明作者及出处,禁止商业使用。
作者:Jerrycyx,原文链接:https://www.cnblogs.com/jerrycyx/p/18331285
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步