150強訪談簡單

在旋轉排序數組中搜尋

「搜尋旋轉排序數組」問題的詳細指南和 Python 實作。

問題陳述

簡單

有一個整數數組 nums 按升序排序(具有不同的值)。在傳遞給函數之前,nums 可能會在未知的主元索引 k (1 <= k < nums.length) 處進行旋轉,從而產生的陣列為 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]

給定可能旋轉後的陣列 nums 和整數 target,如果 target 位於 nums 中,則傳回 target 的索引,如果不在 nums 中,則傳回 target 的索引,如果不在 nums 中,則傳回 -1

您必須編寫一個運行時間複雜度為 O(log n) 的演算法。

寫一個函數 search(nums: List[int], target: int) -> int

約束條件
  • 1 <= len(nums) <= 5000
  • -10^4 <= nums[i] <= 10^4
  • All values of nums are unique
  • nums is an ascending array that is possibly rotated
  • -10^4 <= target <= 10^4

範例

Example 1
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output
4
Explanation

0 is found at index 4.

Example 2
Input
nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output
-1
Explanation

3 is not in the array.

Example 3
Input
nums = [1], target = 0
Output
-1
Explanation

0 is not in the array.

Need a Hint?
考慮使用二分搜尋特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。