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 complete #2009

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
93 changes: 93 additions & 0 deletions Sample
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,98 @@
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this :

NAME: ATHARVA KHARAGE


// Your code here along with comments explaining your approach in three sentences only
PROBLEM 1: 74. Search a 2D Matrix

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix)
n = len(matrix[0])

low = 0
high = (m*n) - 1

while(low <= high):
mid = (low + high) // 2

r = mid // n
c = mid % n

if matrix[r][c] == target: return True

elif matrix[r][c] > target:
high = mid - 1

else:
low = mid + 1

return False

PROBLEM 2: 33. Search in Rotated Sorted Array

class Solution:
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums) - 1

while(low <= high):
mid = (low + high) // 2

if nums[mid] == target: return mid

elif nums[low] <= nums[mid]:
# left sorted
if target >= nums[low] and target < nums[mid]:
high = mid - 1

else:
low = mid + 1

else:
# right sorted
if target > nums[mid] and target <= nums[high]:
low = mid + 1
else:
high = mid - 1

return -1

PROBLEM 3: 702. Search in a Sorted Array of Unknown Size

# """
# 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 * high

while(low <= high):
mid = low + (high - low) // 2

if reader.get(mid) == target: return mid

elif reader.get(mid) > target:
high = mid - 1

else:
low = mid + 1
return -1