0%
Loading ...

【Leetcode 筆記】704. Binary Search

題目解釋

給定一個按 ascending sorted 的整數 array nums 和一個整數 target,寫一個函數在 nums 中搜尋 target

如果 target 存在,則傳回其 index。否則,回傳 -1

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

範例

  • 輸入: nums = [-1, 0, 3, 5, 9, 12], target = 9
  • 輸出: 4

目標 9nums 的第 4 個位置。

最佳解法

看到 O(log n) 就要反射性的想到二元搜尋法 (Binary Search)!

雖然不是 Blind 75
不過在寫 Binary Search 的相關題目時還是建議熟悉一下,
會省事很多~

程式碼

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums) - 1

        while (left <= right):
            mid = left + (right - left) // 2
            if nums[mid] == target:
                return mid
            elif target <= nums[mid]:
                right = mid - 1
            else:
                left = mid + 1

        return -1

時間複雜度

O(logn),n 是 nums 的元素個數。

空間複雜度

O(1)

結語

超高頻的基本題,不可不會!

我朋友說他面 NVIDIA 研替也考了這題,可惡,好羨慕 XD

數據女巫 𝔻.𝕡𝕪𝕤 🔮

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.