150強訪談簡單

尋找旋轉排序數組中的最小值

「尋找旋轉排序數組中的最小值」問題的詳細指南和 Python 實作。

問題陳述

簡單

假設按升序排序的長度為 n 的陣列在 1 到 n 次之間循環。例如,如果陣列 [0,1,2,4,5,6,7] 旋轉 4 次,則可能會變成 [4,5,6,7,0,1,2]

注意,將陣列旋轉 [a[0], a[1], ..., a[n-1]] 1 次會得到 [a[n-1], a[0], a[1], ..., a[n-2]]

給定唯一元素的排序旋轉陣列 nums,傳回該陣列的最小元素。

您必須編寫一個在 O(log n) 時間內執行的演算法。

寫一個函數 findMin(nums: List[int]) -> int

約束條件
  • n == len(nums)
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • All integers in nums are unique
  • nums is sorted and rotated between 1 and n times

範例

Example 1
Input
nums = [3, 4, 5, 1, 2]
Output
1
Explanation

The original array was [1,2,3,4,5] rotated 3 times. The minimum is 1.

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

The original array was [0,1,2,4,5,6,7] rotated 4 times. The minimum is 0.

Example 3
Input
nums = [11, 13, 15, 17]
Output
11
Explanation

Array is not rotated (or rotated n times). The minimum is the first element.

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 資源

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