Skip to content

Done Binary search 1 #2040

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

Open
wants to merge 1 commit 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 matrix_serach_74.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:

if not matrix:
return False
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1

while left <= right:
mid = (left + right) // 2
mid_row, mid_col = divmod(mid, n)

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

return False
30 changes: 30 additions & 0 deletions rotated_sorted_arr_33.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Time Complexity : O(logn)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no

class Solution:
def search(self, nums: List[int], target: int) -> int:

l, r = 0, len(nums) - 1

while l <= r:
mid = l + (r - l) // 2

if nums[mid] == target:
return mid

if nums[l] <= nums[mid]: # check left sorted?
if nums[l] <= target and nums[mid] > target:
r = mid - 1
else:
l = mid + 1
else: # right is sorted

if nums[mid] < target and nums[r] >= target:
l = mid + 1
else:
r = mid - 1
return -1


25 changes: 25 additions & 0 deletions sorted_unknown_lenghth_702.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def search(self, reader, target):
if reader.get(0) == target:
return 0

# search boundaries
l, r = 0, 1
while reader.get(r) < target:
l = r
r = r * 2

# binary search
while l <= r:
mid = l + ((r - l) // 2)
num = reader.get(mid)

if num == target:
return mid
if num > target:
r = mid - 1
else:
l = mid + 1

# there is no target element
return -1