⚡Flashcard Drill➔
NeetCode #285LC-33MediumBinary SearchBlind 75NC 150NC 250
← Back to All Problems

#285 · #33 · Search in Rotated Sorted Array(搜索旋转排序数组)

📌 Problem Statement & Constraints

Given a rotated sorted array of distinct integers nums and a target, return the index of target or -1. Constraints: 1 <= nums.length <= 5000, -10^4 <= nums[i] <= 10^4, all values distinct. The algorithm must run in O(log n).

💡 Core Algorithmic Approaches

  1. At any midpoint, one of the two halves is properly sorted. Determine which by comparing nums[lo] with nums[mid].
  2. If the left half is sorted, check whether the target lies within it; if so, search there, otherwise search the right half.
  3. Symmetrically for the right half. This gives a single binary search.
  4. The key insight is that the rotation point can be located implicitly through the sorted-half test.

💻 Benchmark Python3 Implementation

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        lo, hi = 0, len(nums) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if nums[mid] == target:
                return mid
            if nums[lo] <= nums[mid]:          # left half is sorted
                if nums[lo] <= target < nums[mid]:
                    hi = mid - 1
                else:
                    lo = mid + 1
            else:                              # right half is sorted
                if nums[mid] < target <= nums[hi]:
                    lo = mid + 1
                else:
                    hi = mid - 1
        return -1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(log n): one binary search with O(1) work per step.
💾 Space Complexity
O(1): three indices.

⚠️ Interview Pitfalls & Follow-ups

  • Using nums[lo] < nums[mid] instead of <=: with nums[lo] == nums[mid] (possible when the subarray has one element) the strict version misclassifies the half.
  • Forgetting that only one half is sorted: assuming both halves are sorted leads to an incorrect comparison.
  • Using inclusive comparisons on both ends of the target range: the range test is nums[lo] <= target < nums[mid], half-open, which correctly excludes mid (already checked).
  • Falling back to a linear scan: correct but O(n), defeating the O(log n) requirement.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

搜索旋转排序数组

整数数组 nums 按升序排列,数组中的值 互不相同 。在传递给函数之前,nums 在预先未知的某个下标 k(0 ≤ k &lt; nums.length)上进行了 旋转 。给你 旋转后 的数组 nums 和一个整数 target,如果 nums 中存在这个目标值 target,则返回它的下标,否则返回 −1。你必须设计一个时间复杂度为 O(log n) 的算法解决此问题。约束:1 ≤ nums.length ≤ 5000;-10^4 ≤ nums[i], target ≤ 10^4;nums 中的每个值都独一无二;nums 肯定会在某个点上旋转。

核心要点

  • 先判断哪一半有序,再判断 target 是否落在有序半区(标准解) :取 mid 后, [l, mid] 与 [mid+1, r] 中至少有一半是有序的。
  • 判断有序半 :若 nums[l] &lt;= nums[mid] ,则左半 [l, mid] 有序;否则右半有序。
  • 在有序半中判断 target 是否在范围内 :若在,则把搜索范围收缩到该半区;否则收缩到另一半区。
  • 为什么这样能保持 O(log n) :每次迭代都能确定性地排除一半区间。

常见陷阱

  • 有序半的判断写成 nums[l] &lt; nums[mid] :用 &lt;= 更稳健(当 l == mid 时左半只有一个元素,视为有序)。
  • 范围判断的边界写成闭区间 :必须写成 nums[l] &lt;= target &lt; nums[mid] (左闭右开),因为 nums[mid] == target 已在前面处理过。写成 &lt;= nums[mid] 会重复判断但不影响正确性;写成 target &lt; nums[l] 则完全错误。
  • 先找最小值再二分 :可行(先用 153 的思路找旋转点,再在对应半区二分),需要两趟二分;本解一趟即可。
  • 数组未旋转时 :此时 nums[l] &lt;= nums[mid] 恒成立,退化为普通二分,正确。

参考实现

class Solution:
    def search(self, nums: list[int], target: int) -> int:
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if nums[mid] == target:
                return mid

            if nums[l] <= nums[mid]:
                # 左半 [l, mid] 有序
                if nums[l] <= target < nums[mid]:
                    r = mid - 1
                else:
                    l = mid + 1
            else:
                # 右半 [mid, r] 有序
                if nums[mid] < target <= nums[r]:
                    l = mid + 1
                else:
                    r = mid - 1
        return -1