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 Done #2170

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
23 changes: 23 additions & 0 deletions 2D.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if matrix == None and len(Matrix) == 0:
return False
m = len(matrix)
n = len(matrix[0])
low = 0
high = (m*n) - 1
while low <= high:
mid = low + (high-low)//2
row = mid//n
col = mid%n
if matrix[row][col] == target:
return True
elif target > matrix[row][col]:
low = mid + 1
else:
high = mid - 1
return False


# time = O(log mn)
# space = O(1)
26 changes: 26 additions & 0 deletions Rotated_Sorted_Array.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution:
def search(self, nums: List[int], target: int) -> int:
if nums == None or len(nums) == 0:
return -1
n = len(nums)
low = 0
high = n-1

while low <= high:
mid = low + (high - low)//2
if target == nums[mid]:
return mid
if nums[low] <= nums[mid]:
if nums[low] <= target and nums[mid] > target:
high = mid - 1
else:
low = mid + 1
else:
if nums[high] >= target and nums[mid] < target:
low = mid + 1
else:
high = mid-1
return -1

# time = O(log n)
# Space = O(1)
29 changes: 29 additions & 0 deletions Unknown_Length.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
#class ArrayReader:
# def get(self, index: int) -> int:

class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
low = 0
high = 1
while reader.get(high) < target:
low = high
high *= 2
return self.binarySearch(reader, target, low, high)

def binarySearch(self, reader: 'ArrayReader', target: int, low: int, high: int) -> int:
while low <= high:
mid = low + (high-low)//2
if reader.get(mid) == target:
return mid
elif reader.get(mid) < target:
low = mid + 1
else:
high = mid - 1
return -1

# time = O(log n)
# space = O(1)