150強訪談簡單

二分查找

“二分查找”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個按升序排序的整數陣列 nums 和一個整數 target,寫一個函數在 nums 中搜尋 target。如果 target 存在,則傳回其索引。否則,返回 -1

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

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

約束條件
  • 1 <= len(nums) <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order

範例

Example 1
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
Explanation

9 exists in nums and its index is 4.

Example 2
Input
nums = [-1, 0, 3, 5, 9, 12], target = 2
Output
-1
Explanation

2 does not exist in nums so return -1.

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

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