当前位置:网站首页>通过快排O(n)内查找第K大元素思路
通过快排O(n)内查找第K大元素思路
2022-06-09 20:48:00 【赵寒】
O(n) 时间复杂度内求无序数组中的第 K 大元素。
比如,4, 2, 5, 12, 3 这样一组数据,第 3 大元素就是 4。
我们选择数组区间 A[0...n-1]的最后一个元素 A[n-1]作为 pivot,对数组 A[0...n-1]原地分区,这样数组就分成了三部分,A[0...p-1]、A[p]、A[p+1...n-1]。如果 p+1=K,那 A[p]就是要求解的元素;如果 K>p+1, 说明第 K 大元素出现在 A[p+1...n-1]区间,我们再按照上面的思路递归地在 A[p+1...n-1]这个区间内查找。同理,如果 K<p+1,那我们就在 A[0...p-1]区间查找。
我们再来看,为什么上述解决思路的时间复杂度是 O(n)?
第一次分区查找,我们需要对大小为 n 的数组执行分区操作,需要遍历 n 个元素。第二次分区查找,我们只需要对大小为 n/2 的数组执行分区操作,需要遍历 n/2 个元素。依次类推,分区遍历元素的个数分别为、n/2、n/4、n/8、n/16.……直到区间缩小为 1。
如果我们把每次分区遍历的元素个数加起来,就是:n+n/2+n/4+n/8+...+1。这是一个等比数列求和,最后的和等于 2n-1。所以,上述解决思路的时间复杂度就为 O(n)。
你可能会说,我有个很笨的办法,每次取数组中的最小值,将其移动到数组的最前面,然后在剩下的数组中继续找最小值,以此类推,执行 K 次,找到的数据不就是第 K 大元素了吗?不过,时间复杂度就并不是 O(n) 了,而是 O(K * n)。
你可能会说,时间复杂度前面的系数不是可以忽略吗?O(K * n) 不就等于 O(n) 吗?这个可不能这么简单地划等号。当 K 是比较小的常量时,比如 1、2,那最好时间复杂度确实是 O(n);但当 K 等于 n/2 或者 n 时,这种最坏情况下的时间复杂度就是 O(n2) 了。
边栏推荐
- Go 1.18 新特性 - 工作区
- Share 16 useful typescript and JS tips
- Who says redis can't save big keys
- maximum likelihood estimation
- How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
- Mr. wuyaohui, the world pioneer of ordinary ternary logic mathematics, announced the scientific research achievements of all truth tables of ordinary ternary logic mathematics to the world (Wu's law)
- Mysql异常:The server time zone value‘XXX'解决
- Idea:new no class
- 源代码数据防泄露解决方案分析
- Latex数学符号大全
猜你喜欢

C language to realize computer automatic shutdown program -- it can be used to spoof roommate's computer

Just learning embedded, I want to ask what is interrupt and what is the concept of interrupt

unbutu配置DHCP服务器及客户端连接

MySQL exception: the server time zone value 'xxx' solution

Fanwei oa8 foreground SQL injection

实例:用C#.NET手把手教你做微信公众号开发(19)--使用微信支付转账到微信粉丝零钱账户

多线程场景下使用 ArrayList 丢数据

Typescript variable declaration

(上)苹果有开源,但又怎样呢?

Lambda Exception
随机推荐
LeetCode 497. Random points in non overlapping rectangles**
Numpy duplicate data
ASP. Net mobile terminal inventory system, source code sharing
从源码解析flutter_redux 的精准局部刷新
Daily question - leecode59 (spiral matrix II)
Figure guessing game in C language
Programming question: count the letters that appear most frequently in the string
实例:用C#.NET手把手教你做微信公众号开发(19)--使用微信支付转账到微信粉丝零钱账户
C # learning about abstract classes
Application of anonymous function in C #
Force buckle 84- the largest rectangle in the histogram (monotone stack)
Kubevirt network source code analysis (3) - virtual machine hot migration network
搭建ngrok服务器,实现内网穿透服务,实现外网到内网的在线访问
Gbase8s database select Clause 3
部署 cinder-csi-plugin 遇到的几个问题
为什么要重写equals和hashcode?
Quickly understand the implementation of server IO
Heap (priority queue)
charles抓包-iphone
Go 调用 Kubernetes API 的 几个简单的 example