LeetCode 筆記 - 704. Binary Search

題目在此 704. Binary Search

給一個數列,實作 Binary Search 找出 target 的 index

解題思維

就實作 Binary Search 就可以了

完成✅

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return -1

length = len(nums)

start = 0
end = length - 1

while start <= end:
mid = int((start + end) / 2)

if nums[mid] == target:
return mid
elif nums[mid] < target:
start = mid + 1
else:
end = mid - 1

return -1

也許你也會想看看