mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-14 03:22:23 +08:00
deploy
This commit is contained in:
@ -3639,7 +3639,7 @@
|
||||
<p align="center"> 图 10-5 线性查找重复元素的插入点 </p>
|
||||
|
||||
<p>此方法虽然可用,但其包含线性查找,因此时间复杂度为 <span class="arithmatex">\(O(n)\)</span> 。当数组中存在很多重复的 <code>target</code> 时,该方法效率很低。</p>
|
||||
<p>现考虑拓展二分查找代码。如图 10-6 所示,整体流程保持不变,每轮先计算中点索引 <span class="arithmatex">\(m\)</span> ,再判断 <code>target</code> 和 <code>nums[m]</code> 大小关系:</p>
|
||||
<p>现考虑拓展二分查找代码。如图 10-6 所示,整体流程保持不变,每轮先计算中点索引 <span class="arithmatex">\(m\)</span> ,再判断 <code>target</code> 和 <code>nums[m]</code> 大小关系。</p>
|
||||
<ol>
|
||||
<li>当 <code>nums[m] < target</code> 或 <code>nums[m] > target</code> 时,说明还没有找到 <code>target</code> ,因此采用普通二分查找的缩小区间操作,<strong>从而使指针 <span class="arithmatex">\(i\)</span> 和 <span class="arithmatex">\(j\)</span> 向 <code>target</code> 靠近</strong>。</li>
|
||||
<li>当 <code>nums[m] == target</code> 时,说明小于 <code>target</code> 的元素在区间 <span class="arithmatex">\([i, m - 1]\)</span> 中,因此采用 <span class="arithmatex">\(j = m - 1\)</span> 来缩小区间,<strong>从而使指针 <span class="arithmatex">\(j\)</span> 向小于 <code>target</code> 的元素靠近</strong>。</li>
|
||||
@ -3840,8 +3840,8 @@
|
||||
<p class="admonition-title">Tip</p>
|
||||
<p>本节的代码都是“双闭区间”写法。有兴趣的读者可以自行实现“左闭右开”写法。</p>
|
||||
</div>
|
||||
<p>总的来看,二分查找无非就是给指针 <span class="arithmatex">\(i\)</span> , <span class="arithmatex">\(j\)</span> 分别设定搜索目标,目标可能是一个具体的元素(例如 <code>target</code> ),也可能是一个元素范围(例如小于 <code>target</code> 的元素)。</p>
|
||||
<p>在不断的循环二分中,指针 <span class="arithmatex">\(i\)</span> , <span class="arithmatex">\(j\)</span> 都逐渐逼近预先设定的目标。最终,它们或是成功找到答案,或是越过边界后停止。</p>
|
||||
<p>总的来看,二分查找无非就是给指针 <span class="arithmatex">\(i\)</span> 和 <span class="arithmatex">\(j\)</span> 分别设定搜索目标,目标可能是一个具体的元素(例如 <code>target</code> ),也可能是一个元素范围(例如小于 <code>target</code> 的元素)。</p>
|
||||
<p>在不断的循环二分中,指针 <span class="arithmatex">\(i\)</span> 和 <span class="arithmatex">\(j\)</span> 都逐渐逼近预先设定的目标。最终,它们或是成功找到答案,或是越过边界后停止。</p>
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user