---
# System prepended metadata

title: Leetcode 704. Binary Search
tags: [Leetcode, Binary Search]

---

## 題解

Binary search 的邊界條件一定要確立好，如果不確立好邊界條件就寫，一定會出問題

```python=
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        n = len(nums)
        left, right = 0, n - 1
        while left <= right: # 最後 left 和 right 一定會前後交錯
            mid = left + (right - left) // 2 # 避免溢位
            if nums[mid] > target:
                right = mid - 1
            elif nums[mid] < target:
                left = mid + 1
            else:
                return mid # 查到回傳 index
        return -1 # 查不到 return -1
```