Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary search 1 #2178

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions inf_array_search
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def search(reader: ArrayReader, target):
left, right = 0, 1
while reader.get(right) < (2**31 - 1):
if reader.get(right) >= target:
break
left = right
right *= 2

while left <= right:
mid = left + (right - left) // 2
val = reader.get(mid)

if val == target:
return mid
elif val > target or val == (2**31 - 1):
right = mid - 1
else:
left = mid + 1

return -1
21 changes: 21 additions & 0 deletions matrix_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False

m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1

while left <= right:
mid = (left + right) // 2
row = mid // n
col = mid % n

if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
left = mid + 1
else:
right = mid - 1

return False
27 changes: 27 additions & 0 deletions rotated_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def search(self, nums: List[int], target: int) -> int:

left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2

if target == nums[mid]:
return mid

elif (left == mid == right) :
return -1

elif nums[mid]>=nums[left]:
if nums[left]<=target<nums[mid]:
right = mid
else:
left = mid+1

else:
if nums[mid]<target<nums[left]:
left = mid+1
else:
right = mid
return -1