mirror of
https://github.com/krahets/hello-algo.git
synced 2025-08-03 04:13:40 +08:00
deploy
This commit is contained in:
@ -26,7 +26,7 @@
|
||||
|
||||
|
||||
|
||||
<title>8.3 Top-K 问题 - Hello 算法</title>
|
||||
<title>8.3 Top-k 问题 - Hello 算法</title>
|
||||
|
||||
|
||||
|
||||
@ -126,7 +126,7 @@
|
||||
<div class="md-header__topic" data-md-component="header-topic">
|
||||
<span class="md-ellipsis">
|
||||
|
||||
8.3 Top-K 问题
|
||||
8.3 Top-k 问题
|
||||
|
||||
</span>
|
||||
</div>
|
||||
@ -1730,7 +1730,7 @@
|
||||
|
||||
|
||||
<span class="md-ellipsis">
|
||||
8.3 Top-K 问题
|
||||
8.3 Top-k 问题
|
||||
</span>
|
||||
|
||||
|
||||
@ -1741,7 +1741,7 @@
|
||||
|
||||
|
||||
<span class="md-ellipsis">
|
||||
8.3 Top-K 问题
|
||||
8.3 Top-k 问题
|
||||
</span>
|
||||
|
||||
|
||||
@ -3532,10 +3532,10 @@
|
||||
|
||||
|
||||
<!-- Page content -->
|
||||
<h1 id="83-top-k">8.3 Top-K 问题<a class="headerlink" href="#83-top-k" title="Permanent link">¶</a></h1>
|
||||
<h1 id="83-top-k">8.3 Top-k 问题<a class="headerlink" href="#83-top-k" title="Permanent link">¶</a></h1>
|
||||
<div class="admonition question">
|
||||
<p class="admonition-title">Question</p>
|
||||
<p>给定一个长度为 <span class="arithmatex">\(n\)</span> 的无序数组 <code>nums</code> ,请返回数组中前 <span class="arithmatex">\(k\)</span> 大的元素。</p>
|
||||
<p>给定一个长度为 <span class="arithmatex">\(n\)</span> 的无序数组 <code>nums</code> ,请返回数组中最大的 <span class="arithmatex">\(k\)</span> 个元素。</p>
|
||||
</div>
|
||||
<p>对于该问题,我们先介绍两种思路比较直接的解法,再介绍效率更高的堆解法。</p>
|
||||
<h2 id="831">8.3.1 方法一:遍历选择<a class="headerlink" href="#831" title="Permanent link">¶</a></h2>
|
||||
@ -3555,7 +3555,7 @@
|
||||
<p align="center"> 图 8-7 排序寻找最大的 k 个元素 </p>
|
||||
|
||||
<h2 id="833">8.3.3 方法三:堆<a class="headerlink" href="#833" title="Permanent link">¶</a></h2>
|
||||
<p>我们可以基于堆更加高效地解决 Top-K 问题,流程如图 8-8 所示。</p>
|
||||
<p>我们可以基于堆更加高效地解决 Top-k 问题,流程如图 8-8 所示。</p>
|
||||
<ol>
|
||||
<li>初始化一个小顶堆,其堆顶元素最小。</li>
|
||||
<li>先将数组的前 <span class="arithmatex">\(k\)</span> 个元素依次入堆。</li>
|
||||
@ -3920,7 +3920,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<p>总共执行了 <span class="arithmatex">\(n\)</span> 轮入堆和出堆,堆的最大长度为 <span class="arithmatex">\(k\)</span> ,因此时间复杂度为 <span class="arithmatex">\(O(n \log k)\)</span> 。该方法的效率很高,当 <span class="arithmatex">\(k\)</span> 较小时,时间复杂度趋向 <span class="arithmatex">\(O(n)\)</span> ;当 <span class="arithmatex">\(k\)</span> 较大时,时间复杂度不会超过 <span class="arithmatex">\(O(n \log n)\)</span> 。</p>
|
||||
<p>另外,该方法适用于动态数据流的使用场景。在不断加入数据时,我们可以持续维护堆内的元素,从而实现最大 <span class="arithmatex">\(k\)</span> 个元素的动态更新。</p>
|
||||
<p>另外,该方法适用于动态数据流的使用场景。在不断加入数据时,我们可以持续维护堆内的元素,从而实现最大的 <span class="arithmatex">\(k\)</span> 个元素的动态更新。</p>
|
||||
|
||||
<!-- Source file information -->
|
||||
|
||||
|
Reference in New Issue
Block a user