[ZHOJ1131]Find K Min

本文介绍了一种基于快速排序思想的算法,用于在数列中查找第K大的数。通过不断划分数列并根据目标位置调整搜索方向,实现高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:
  给你一个数列,求其中第K大的数。

思路:
  类似于快速排序的思想,每次可以确定出当前的的x在数组中的位置。
  然后根据位置选择该往左找还是往右找。

 1 #pragma GCC optimize(3)
 2 #include<cstdio>
 3 #include<cctype>
 4 #include<bits/move.h>
 5 inline int getint() {
 6     register char ch;
 7     while(!isdigit(ch=getchar()));
 8     register int x=ch^'0';
 9     while(isdigit(ch=getchar())) x=(((x<<2)+x)<<1)+(ch^'0');
10     return x;
11 }
12 const int N=10000001;
13 int a[N];
14 int find(const int &l,const int &r,const int &k) {
15     int i=l,j=r;
16     const int x=a[(l+r)>>1];
17     do {
18         while(a[i]<x) i++;
19         while(a[j]>x) j--;
20         if(i<=j) std::swap(a[i++],a[j--]);
21     } while(i<=j);
22     if(l<=k&&k<=j) return find(l,j,k);
23     if(i<=k&&k<=r) return find(i,r,k);
24     return x;
25 }
26 int main() {
27     int n=getint(),k=getint();
28     for(register int i=1;i<=n;i++) {
29         a[i]=getint();
30     }
31     printf("%d\n",find(1,n,k));
32     return 0;
33 }

 

转载于:https://www.cnblogs.com/skylee03/p/7655791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值