-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.py
More file actions
34 lines (25 loc) · 752 Bytes
/
Copy pathbinarySearch.py
File metadata and controls
34 lines (25 loc) · 752 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# https://leetcode.com/explore/learn/card/binary-search/138/background/1038/
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums) == 1:
if target == nums[0]:
return 0
else:
return -1
l = 0
h = len(nums) - 1
while l <= h:
mid = (l+h) // 2
if nums[mid] == target:
return mid
elif nums[l] == target:
return l
elif nums[h] == target:
return h
if target > nums[mid]:
l = mid + 1
elif target < nums[mid]:
h = mid - 1
else:
break
return -1