-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch_704_binarySearch.py
65 lines (43 loc) · 1.54 KB
/
binarySearch_704_binarySearch.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
https://leetcode.com/problems/binary-search/
leetcode 704
easy
iterative approach
input : an array of integers nums which is sorted in ascending order, and an integer target
output: 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.
Logic : use iterative approach and avoid overflow while calculating mid
Time Complexity: o(logn) since array divided by 2 at each step
"""
class Solution:
def search(self, nums: List[int], target: int) -> int:
# simple binary search
l=0
r=len(nums)-1
while l<=r: #remember this is <= else l at last position will not work
mid = (l+r)//2
if nums[mid]==target:
return mid
elif target > nums[mid]:
l=mid+1
else :
r = mid-1
return -1
obj = Solution()
print(obj.search([2,5],5))
# class Solution: (with detailed comments)
# def search(self, nums, target: int) -> int:
# # search space is entire array
# l=0
# r=len(nums)-1
# # iterative
# while(l<=r):
# mid = l + ((r-l)//2) #to avoid overflow
# if nums[mid] == target : #target found
# return mid
# elif nums[mid] > target : #search left
# r = mid-1
# elif nums[mid] < target : #search right
# l = mid + 1
# # if target not found
# return -1