704. Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.

規則

給予一個數字 target 和一個數組 nums,如果 nums 中存在 target,則返回 target 的索引,反之返回 -1。

測試案例

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

思路

  1. 取出中間值
  2. 如果 low > high ,則代表沒找到,回傳 -1
  3. 如果中間值等於 target,命中則回傳
  4. 如果中間值大於 target,則從中間值開始往左找
  5. 如果中間值小於 target,則從中間值開始往右找

實作

def search(self, nums, target) -> int:
    return self.helper(nums, 0, len(nums) - 1, target)
def helper(self, nums, low, high, target):
    mid = (low + high) // 2 # 取整數
    if low > high: # 沒找到
        return -1
    if nums[mid] == target: # 命中
        return mid
    if nums[mid] > target: # 從左邊找
        high = mid - 1 # 從中間值開始往左找
    if nums[mid] < target: # 從右邊找
        low = mid + 1 # 從中間值開始往右找
    return self.helper(nums, low, high, target)