File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -603,6 +603,44 @@ class Solution:
603603- 时间复杂度:$$ O(log N) $$
604604- 空间复杂度:$$ O(1) $$
605605
606+ ##### 扩展
607+
608+ 如果题目不是让你返回 true 和 false,而是返回最左/最右等于 targrt 的索引呢?这不就又和前面的知识建立联系了么?比如我让你在一个旋转数组中找最左等于 target 的索引,其实就是 [ 面试题 10.03. 搜索旋转数组] ( https://leetcode-cn.com/problems/search-rotate-array-lcci/ ) 。
609+
610+ 思路和前面的最左满足类似,仍然是通过压缩区间,更新备胎,最后返回备胎的方式来实现。 具体看代码吧。
611+
612+ Python Code:
613+
614+ ``` py
615+ class Solution :
616+ def search (self , nums : List[int ], target : int ) -> int :
617+ l, r = 0 , len (nums) - 1
618+ while l <= r:
619+ mid = l + (r - l) // 2
620+ # # the first half is ordered
621+ if nums[l] < nums[mid]:
622+ # target is in the first half
623+ if nums[l] <= target <= nums[mid]:
624+ r = mid - 1
625+ else :
626+ l = mid + 1
627+ # # the second half is ordered
628+ elif nums[l] > nums[mid]:
629+ # target is in the second half
630+ if nums[l] <= target or target <= nums[mid]:
631+ r = mid - 1
632+ else :
633+ l = mid + 1
634+ elif nums[l] == nums[mid]:
635+ if nums[l] != target:
636+ l += 1
637+ else :
638+ # l 是一个备胎
639+ r = l - 1
640+ return l if l < len (nums) and nums[l] == target else - 1
641+
642+ ```
643+
606644### 二维数组
607645
608646二维数组的二分查找和一维没有本质区别, 我们通过两个题来进行说明。
You can’t perform that action at this time.
0 commit comments