如何在 O(n) 中找到长度为 n 的未排序数组中的第 k 个最大元素?

编程入门 行业动态 更新时间:2024-10-26 02:34:02
本文介绍了如何在 O(n) 中找到长度为 n 的未排序数组中的第 k 个最大元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我相信有一种方法可以在 O(n) 的长度为 n 的未排序数组中找到第 k 个最大的元素.或者它可能是预期的"O(n) 之类的.我们该怎么做?

I believe there's a way to find the kth largest element in an unsorted array of length n in O(n). Or perhaps it's "expected" O(n) or something. How can we do this?

推荐答案

这称为查找 k 阶统计量.有一个非常简单的随机算法(称为 quickselect),采用 O(n) 平均时间,O(n^2) 最坏情况时间,以及一个非常复杂的非随机算法(称为 introselect),它采用 O(n) 最坏情况时间.有一些关于维基百科的信息,但不是很好.

This is called finding the k-th order statistic. There's a very simple randomized algorithm (called quickselect) taking O(n) average time, O(n^2) worst case time, and a pretty complicated non-randomized algorithm (called introselect) taking O(n) worst case time. There's some info on Wikipedia, but it's not very good.

您需要的一切都在 这些幻灯片.只是为了提取O(n)最坏情况算法(introselect)的基本算法:

Everything you need is in these powerpoint slides. Just to extract the basic algorithm of the O(n) worst-case algorithm (introselect):

Select(A,n,i): Divide input into ⌈n/5⌉ groups of size 5. /* Partition on median-of-medians */ medians = array of each group’s median. pivot = Select(medians, ⌈n/5⌉, ⌈n/10⌉) Left Array L and Right Array G = partition(A, pivot) /* Find ith element in L, pivot, or G */ k = |L| + 1 If i = k, return pivot If i < k, return Select(L, k-1, i) If i > k, return Select(G, n-k, i-k)

在 Cormen 等人的《算法导论》一书中也非常详细.

It's also very nicely detailed in the Introduction to Algorithms book by Cormen et al.

更多推荐

如何在 O(n) 中找到长度为 n 的未排序数组中的第 k 个最大元素?

本文发布于:2023-11-29 17:38:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序数   组中   长度为   元素   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!