-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search.py
More file actions
36 lines (29 loc) · 1.07 KB
/
Copy pathBinary Search.py
File metadata and controls
36 lines (29 loc) · 1.07 KB
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
35
36
class Solution:
def search(self, nums: List[int], target: int) -> int:
def binarySearch(nums, left, right, target):
if right>=left:
halfIndex = floor((left+right)/2)
if nums[halfIndex] == target:
return halfIndex
elif nums[halfIndex] > target:
right = halfIndex - 1
return binarySearch(nums, left, right, target)
elif nums[halfIndex] < target:
left = halfIndex + 1
return binarySearch(nums, left, right, target)
else:
return -1
return binarySearch(nums, 0, len(nums) -1, target)
#Iterative solution - >>>
# class Solution:
# def search(self,nums:List[int],target:int)->int:
# 1,r=0,len(nums)-1
# while1<=r:
# m=(1+r)//2
# if nums[m]>target:
# r=m-1
# elif nums[m]<target:
# 1=m+1
# else:
# returnm
# return -1